models.py
class Match(models.Model):
match_name = models.CharField(max_length=100)
player = models.CharField(max_length=100, choices=match_game, default=2)
time_start = models.DateTimeField(blank=True, default=None, null=True)
match_finished = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse('match:details', kwargs={'pk': self.pk})
def __str__(self):
return self.match_name
class PlayerSignup(models.Model):
current_player = models.ForeignKey(User)
signup = models.ForeignKey(Match)
urls.py
url(r'^create/add/$', views.MatchCreate.as_view(), name='match-add'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(template_name = 'match/bracket_detail.html'), name='details'),
url(r'^search/$', views.IndexView.as_view(template_name = 'match/bracket.html'), name='search'),
url(r'(?P<pk>[0-9]+)/$', views.PlayerSign, name='join')
views.py
def PlayerSign(request):
model = PlayerSignup.objects.all()
match = Match.objects.get(pk=Match.pk)
joinmatch = PlayerSignup(current_player=request.user, signup=match)
joinmatch.save()
return render(request, 'match/bracket_detail.html', {'model': model })
template
Join Match
when a person clicks on the 'Join Match' link i would like it to create a PlayerSignup model and link it to the current match that they are on.
when i click the Join Match link nothing happens, no new model, no error
First, try to edit this statement
def PlayerSign(request):
...
match = Match.objects.get(pk=Match.pk)
to
def PlayerSign(request, pk):
...
match = Match.objects.get(pk=pk)
Because there is an request parameter in URL named pk, you should pass this parameter to the query method.
Second, review your url define
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(template_name = 'match/bracket_detail.html'), name='details'),
url(r'(?P<pk>[0-9]+)/$', views.PlayerSign, name='join')
Change to
url(r'^match_detail/(?P<pk>[0-9]+)/$', views.DetailView.as_view(template_name = 'match/bracket_detail.html'), name='details'),
url(r'^player_detail/(?P<pk>[0-9]+)/$', views.PlayerSign, name='join')
Related
I have a view AsignacionGeneral from where I call the view assignacion_contact with href="{% url 'gestionAsignacion:assignacion_contact' pk=asig.id %} and pass the parameter by url which is the primary key to be inserted later in the foreign key idasignacion_general = models.ForeignKey('AsignacionGeneral', models.DO_NOTHING, db_column='idasignacion_general') , the view assignacion_contact has a form, it opens fine, I fill the form but when I send it I want it to stay in the same view.
example: I am in the url "assignation/assignationContact/1", the pk=1 , I take that value and assign it to the Foreign Key, I fill the form with the data but when I send it it redirects me to 'assignation/assignationContact' which does not exist and I want it to stay in the url ' 'asignacion/asignacionContact/1'
error image
url.py
app_name = 'gestionAsignacion'
urlpatterns = [
path('asignacionContact/<int:pk>',AsignacionCreateView.as_view(), name='asignacion_contact'),
path('detalle/asignacion/<int:pk>',descargarAsignacion.as_view(), name='descargar_asignacion'),
path('asignacionGeneral/',asignacionGeneral.as_view(), name='asignacion_general'),
]
view.py
class AsignacionCreateView(CreateView):
model=AsignacionContact
form_class=AsignacionForm
template_name='gestionAsignacion/asignacion_contact.html'
# success_url = reverse_lazy('gestionAsignacion:asignacion_general')
def get_initial(self):
# call super if needed
return {'idasignacion_general': self.kwargs['pk']}
def form_valid(self, form):
print('hola form_valid')
isvalid = super().form_valid(form)
return isvalid
def get_success_url(self):
return HttpResponseRedirect(reverse('gestionAsignacion:asignacion_general'))
def get_context_data(self, **kwargs):
# Llame primero a la implementación base para obtener un contexto
context = super().get_context_data(**kwargs)
# Agregar un QuerySet de todos los libros
context['asig_general'] = AsignacionGeneral.objects.get(id=self.kwargs['pk'])
context['object_list'] = AsignacionContact.objects.filter(idasignacion_general=self.kwargs['pk'])
return context
model.py
class AsignacionContact(models.Model):
id = models.IntegerField(primary_key=True)
idasignacion_general = models.ForeignKey('AsignacionGeneral', models.DO_NOTHING, db_column='idasignacion_general')
nombre_asignacion = models.CharField(max_length=100, blank=True, null=True)
fecha_inicio = models.DateField(blank=True, null=True)
fecha_fin = models.DateField(blank=True, null=True)
observacion = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return self.nombre_asignacion
class Meta:
managed = False
db_table = 'asignacion_contact'
form.py
class AsignacionForm(ModelForm):
def __init__(self, *args, **kwargs):
super(AsignacionForm, self).__init__(*args, **kwargs)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
'class': 'form-control'
})
class Meta:
model=AsignacionContact
fields=['idasignacion_general','nombre_asignacion','fecha_inicio','fecha_fin','observacion']
This path('asignacionContact/<int:pk>',... means that the primary key of the object is required to show the view.
For example, an object with pk=1 would work for the URL path asignacion/asignacionContact/1.
You don't have a view that's just asignacion/asignacionContact/ in your urls.py.
That's why you are getting a Page not found (404).
I think you think <int:pk> in urls.py are GET querystrings. They are not. They are required URL values. GET parameters appear appended to the URL for example if you were to submit a form with a method="GET". The form data would appear in the URL.
My DB (MariaDB) is set to utf8mb4, my model and my view are all defined to use unicode characters.
The creation of the record is ok and a slug is correctly created with a value as for example corée. The problem raise right after the creation with a NoReverse match error msg. I had a look to the documentation but I don't understand what I'm doing wrong. Thanks for your support.
NoReverseMatch at /masterdat/countrycode/
Reverse for 'countrycode_update' with keyword arguments '{'slug': 'corée'}' not found. 1 pattern(s) tried: ['masterdat/countrycode/(?P[-a-zA-Z0-9_]+)/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/masterdat/countrycode/
Django Version: 3.2.5
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'countrycode_update' with keyword arguments '{'slug': 'corée'}' not found. 1 pattern(s) tried: ['masterdat/countrycode/(?P[-a-zA-Z0-9_]+)/$']
URL:
from django.urls import path
from masterdat import views
from masterdat.views import CountrycodeListView
from masterdat.views import CountrycodeCreateView, CountrycodeUpdateView
urlpatterns = [
path('masterdathome/', views.masterdathome, name='masterdathome'),
path('countrycode/', CountrycodeListView.as_view(),
name='countrycode_list'),
path('countrycode/add/', CountrycodeCreateView.as_view(),
name='countrycode_add'),
path('countrycode/<slug:slug>/', CountrycodeUpdateView.as_view(),
name='countrycode_update'),
]
Model:
class Countrycode(models.Model):
cou_code = models.CharField(
"Country name", max_length=40, primary_key=True)
cou_recblocked = models.BooleanField("Country record blocked")
cou_creator = models.ForeignKey(
User, on_delete=models.PROTECT, related_name='+',
verbose_name="Created by")
cou_creationdate = models.DateTimeField("Creation date",
auto_now=True)
cou_modifier = models.ForeignKey(
User, on_delete=models.PROTECT, related_name='+',
verbose_name="Last modification by")
cou_modified = models.DateTimeField(
"Last modification date", auto_now=True)
slug = models.SlugField(max_length=50, allow_unicode=True)
class Meta:
ordering = ["cou_code"]
def __str__(self):
return self.cou_code
def get_absolute_url(self):
return reverse('countrycode_update', kwargs={'slug': self.slug})
View:
from masterdat.models import Countrycode
#-----------------------
# List view Management
#-----------------------
class CountrycodeListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
permission_required = 'masterdat.view_countrycode'
model = Countrycode
paginate_by = 10
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
return context
# Search bar
def get_queryset(self):
result = super(CountrycodeListView, self).get_queryset()
query = self.request.GET.get('q')
if query:
query_list = query.split()
result = result.filter(
reduce(operator.and_,
(Q(cou_code__icontains=q) for q in query_list))
)
return result
#-----------------------------------
# Create and Update Views Management
#-----------------------------------
from masterdat.forms import CountrycodeForm
# Create View -----------
class CountrycodeCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
permission_required = 'masterdat.add_countrycode'
model = Countrycode
form_class = CountrycodeForm
success_url = reverse_lazy('countrycode_list')
def form_valid(self, form):
form.instance.slug = slugify(form.instance.cou_code, allow_unicode=True)
form.instance.cou_creator = self.request.user
form.instance.cou_modifier = self.request.user
form.save
return super().form_valid(form)
# Update View -----------
class CountrycodeUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
permission_required = 'masterdat.change_countrycode'
model = Countrycode
form_class = CountrycodeForm
success_url = reverse_lazy('countrycode_list')
def form_valid(self, form):
form.instance.cou_modifier = self.request.user
form.save
return super().form_valid(form)
The regular expression (?P[-a-zA-Z0-9_]+) will only match "cor" because "é" is not a member of the range "A-Z" or "a-z".
You could change it to (?P[-\w0-9_]+) to match non-ASCII characters.
I am building off of the question listed here: How can I use get_next_by_FOO() in django?
I have altered the code for my project (see below), but when I click on "next" to hyperlink to the next object in my Picture model the same page only reloads. Can someone tell me what I am doing wrong?
Models.py
class Picture(models.Model):
name = models.CharField(max_length=100)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
image = models.ImageField(upload_to='photo/')
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('picture-detail', kwargs={ 'pk': self.pk })
views.py
class PictureDetailView(DetailView):
model = Picture
def picture_detail(request, id=None):
instance = get_object_or_404(Picture, id=id)
the_next = instance.get_next_by_date_posted()
context = {
'name': instance.name,
'instance': instance,
'the_next': the_next,
}
return render(request, 'gallery/picture_detail.html', context)
urls.py
urlpatterns = [
path('', views.home, name='gallery-home'),
path('picture/', PictureListView.as_view(), name='gallery-picture'),
path('picture/<int:pk>/', PictureDetailView.as_view(), name='picture-detail'),
]
picture_detail.html
Next
You need to obtain the get_absolute_url of the next instance. the_next is only a Picture, not its link, so:
Next
I have built a guide website.
Each guide is made of steps.
Each step is made of tasks.
To go the next step, you need to complete the task and then to the next, until there are no more steps.
Example views and URL:
/1 should show you guide1
/1/3 should show the step3 of guide1
/1/3/5 should show task5 of step3 in guide1
I want the URLs to be like this: /1/3/6 (guide1/step3/task6)
I got it to work when I go to /1. Then it shows the view of the guide.
But when I go to /1/1 or 1/1/1 I get a 404 error saying that the guide does not exist.
I need help. Here is my code:
Urls.py for app
urlpatterns = [
url(r'(?P<guide_id>[0-9]+)/$', views.taskoftheday, name="taskoftheday"),
url(r'(?P<guide_id>[0-9]+)/(?P<step.sequence_num>[0-9]+)/$', views.taskoftheday_step, name="taskoftheday_step"),
url(r'(?P<guide_id>[0-9]+)/(?P<step.sequence_num>[0-9]+)/(?P<task.sequence_num>[0-9]+)/$', views.taskoftheday_task, name="taskoftheday_task"),
]
urls.py for project
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('registration.urls')),
url(r'^taskoftheday/', include('taskoftheday.urls')),
url(r'^', include('taskoftheday.urls')),
url(r'^analytics/', include('analytics.urls')),
url(r'^progress/', include('progress.urls')),
url(r'^goals/', include('goals.urls')),
url(r'^registration/', include('registration.urls')),
url(r'thanks/', views.thanks),
url(r'thanks_again/', views.thanks_again),
url(r'^$', views.landing_page),
]
models.py
class Guide(models.Model):
name = models.CharField(max_length=200)
guide_category = models.CharField(max_length=70)
guide_why = models.TextField()
guide_how = models.TextField()
is_complete = models.BooleanField(default=False)
def __unicode__(self):
return self.name
class Step(models.Model):
guide = models.ForeignKey(Guide, on_delete=models.CASCADE)
sequence_number = models.PositiveIntegerField(default=1)
name = models.CharField(max_length=10)
is_complete = models.BooleanField(default=False)
class Meta:
unique_together = ("guide", "sequence_number")
def __unicode__(self):
return self.name
class Task(models.Model):
step = models.ForeignKey(Step, on_delete=models.CASCADE)
sequence_number = models.PositiveIntegerField(default=1)
name = models.CharField(max_length=10)
task_img = models.ImageField()
task_task = models.TextField()
task_description = models.TextField()
is_complete = models.BooleanField(default=False)
class Meta:
unique_together = ("step", "sequence_number")
def __unicode__(self):
return self.name
views.py
def taskoftheday(request, guide_id):
try:
guide = Guide.objects.get(pk=guide_id)
except Guide.DoesNotExist:
raise Http404("Guide does not exist")
return render(request, 'taskoftheday/taskoftheday.html', {'guide': guide})
def taskoftheday_step(request, guide_id, step_id):
try:
guide = Guide.objects.get(pk=guide_id)
step = Step.objects.get(guide=guide, sequence_number=step_id)
except Step.DoesNotExist:
raise Http404("Step does not exist")
return render(request, 'taskoftheday/taskoftheday_step.html', {'step': step})
def taskoftheday_task(request, guide_id, step_id, task_id):
try:
guide = Guide.objects.get(pk=guide_id)
step = Step.objects.get(guide=guide, sequence_number=step_id)
task = Task.objects.get(step=step, sequence_number=task_id)
except Task.DoesNotExist:
raise Http404("Task does not exist")
return render(request, 'taskoftheday/taskoftheday_task.html', {'task': task})
Simplified version of forum app in Django. What I want to do is have an url in the form of forum/forum_slug/thread_slug/. I have no idea how to define and pass the custom forum_slug to urlpatterns.
# models.py
class Forum(models.Model):
title = models.CharField(max_length=60)
slug = models.CharField(max_length=60)
# ...
def threads(self):
_threads = Thread.objects.filter(forum=self)
return _threads
class Thread(models.Model):
title = models.CharField(max_length=60)
slug = models.CharField(max_length=60)
forum = models.ForeignKey(Forum)
# ...
def get_absolute_url(self):
return '/%s/%s' % (self.forum.slug, self.slug)
class Post(models.Model):
title = models.CharField('Title', max_length=60)
thread = models.ForeignKey(Thread)
# ...
# ******************************************************
# views.py
# ******************************************************
class ForumDetail(MetadataMixin, DetailView):
model = Forum
context_object_name = 'forum'
template_name = 'forum/forum.html'
name='forum'
# meta...
class ThreadDetail(MetadataMixin, DetailView):
model = Thread
context_object_name = 'thread'
template_name = 'forum/thread.html'
name = 'thread'
# meta...
# ******************************************************
# urls.py
# ******************************************************
urlpatterns = patterns('',
url(r'^$',
'forum.views.index',
name='index'
),
url(r'^(?P<slug>[a-zA-Z0-9-]+)/?$',
ForumDetail.as_view()),
# here it comes
url(r'^(?P<forum_slug>[a-zA-Z0-9-]+/?P<slug>[a-zA-Z0-9-]+)/?$',
ThreadDetail.as_view()),
)
I assume that you want URL pattern for slugs. Below is the example you can try.
# URL example: /forum/this-is-a-forum-1/this-is-a-thread-1/
url(r'^forum/(?P<forum_slug>[\w-]+)/(?P<thread_slug>[\w-]+)$', ThreadDetail.as_view()),
Hope this helps.
#rayy: Thanks. No, this is not what I was looking for -- I simply do not know how to define forum_slug in it. That's what I was asking for. :-) Well, I figured out kinda more verbose solution but, frankly, I do not like it:
# models.py
from django.core.urlresolvers import reverse
class Thread(models.Model):
#... like before
def get_absolute_url(self):
return reverse('thread_url', (), {'forum_slug': self.forum.slug, 'slug': self.slug})
# urls.py
urlpatterns = patterns('',
# ...
url(r'^(?P<forum_slug>[\w-]+)/(?P<slug>[\w-]+)/$', ThreadDetail.as_view(), name='thread_url'),)
# index.html / forum.html (in a loop)
{{thread.title}}