Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get Distinct object with sorted from lowest value to highest value in django
I want to sort the filter value from lowest to highest in Django. Here I'm getting this output: Now in this filter list, I want to show data to be filtered in ascending order and the blank data and none data to be not shown in o/p. something like this: cores [] 2 [] 4 [] 6 [] 8 . . . I try to code some this way. views.py filter_cores = Processor.objects.distinct().values('cores') How it will be filtered data in ascending order and I tried filter_cores = Processor.objects.distinct().values('cores').order_by('cores') but it scrambled data and nothing else. -
Cannot import '<app_name>'. Check that '<Config>' is correct
Given is my folder structure. In 'urls.py' of project- urlpatterns = [ path('admin/', admin.site.urls), path('', include('apps.job_main.urls')), ] In settings.py- INSTALLED_APPS = [ 'django.contrib.admin', . . 'apps.job_main' ] Complete error pastebin link Is my import correct or any suggestions would be helpful? Django Version=3.2.4 -
How to annotate the same value multiple times in django?
How to perform nested annotation on the same field. Example: Say you have two querysets that are a result of annotation, where foo is the annotation field qs1 = [ {user:1, foo:30}, {user:2, foo:10} ] qs2 = [ {user:1, foo:7}, {user:2, foo:5} ] after the combination of the querysets, I need to annotate a field called sum. combined = qs1 | qs2 result = combined.annotate(Sum('foo')) # The result of annotation will be print(result) [{user: 1, foo__sum: 37}, {user:2, foo__sum: 15}] But when attempting to do so, I get an error: FieldError: Cannot compute Sum('foo'): 'foo' is an aggregate -
How To Use Query Inside Django Model?
I Have 2 Different Django Model User_detials and Monthly_payment and now I want to make the Status= Active, Expire, Soon Expire, or Deactivated, in User details i am trying this but not work ho to make using 2 different model different fields using username and received date is any solution ?? here is my model class Client_Detials(models.Model, object): First_name = models.CharField(max_length=100) Last_name = models.CharField(max_length=100) Address = models.CharField(max_length=100) Contact_1 = models.CharField(max_length=100) Contact_2 = models.CharField(max_length=100) Email = models.EmailField() Username = models.CharField(max_length=20) Password = models.CharField(max_length=20) cont_type = ( ('Fiber', 'Fiber'), ('wireless', 'wireless'), ) Connection_Type = models.CharField(choices=cont_type, max_length=12, default='Fiber') Internet_Plan = models.ForeignKey(Nas_Package, on_delete=models.CASCADE) Payment_Cycle = models.CharField(max_length=100, blank=True) User_Img = models.ImageField(upload_to='Client', default='user.jpg', blank=True) Created_by = models.OneToOneField(User, on_delete=models.CASCADE) Created_Date = models.DateTimeField(auto_now=True) def status(self): recharge = recharge_monthly.username if recharge == self.Username: date_to_re = recharge_monthly.received_date myd = datetime.datetime.now().date() - date_to_re print(myd) if myd.days < 20: return "Active" elif myd.days < 25: return "Expire Soon" elif myd.days <= 30: return "Expire" else: return "Expire From {} day".format(30 - myd.days) class recharge_monthly(models.Model): username = models.ForeignKey(Client_Detials, on_delete=models.CASCADE) Total_amount = models.FloatField() Received_amount = models.FloatField(default=0.0) received_date = models.DateField(auto_now_add=True) is_vat_add = models.BooleanField() is_tsc_add = models.BooleanField() tsc_amount = models.FloatField() vat_amount = models.FloatField() -
Django Prefetch Related use effectively in Template
I have two models Quiz and Sitting Models.py class Quiz(models.Model): title = models.CharField(verbose_name=_("Title"),max_length=300, blank=False) description = models.TextField(verbose_name=_("Description"),blank=True, help_text=_("a description of the quiz")) url = models.SlugField(max_length=60, blank=False,help_text=_("a user friendly url"), verbose_name=_("user friendly url"),default=uuid.uuid4) class Sitting(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_("User"), on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, verbose_name=_("Quiz"), on_delete=models.CASCADE) views.py from django.db.models import Prefetch def getTestFest(request): if request.method == "GET" and request.is_ajax(): examtype = request.GET.get('examtype') print(examtype) if examtype=='M': exams = Quiz.objects.filter(Q(draft=False) ).prefetch_related(Prefetch('sitting_set',queryset=Sitting.objects.filter(user=request.user))).all() else: exams = Quiz.objects.filter(Q(draft=False)).prefetch_related(Prefetch('sitting_set',queryset=Sitting.objects.filter(user=request.user))).all() context={ "exams": exams, } #exams.filter(sitting.user==request.user) print(exams) return render(request, 'testfest/exams.html',context) My Template: {% for exam in exams %} <div > {% for sitting in exam.sitting_set.all%} {% if sitting %} Exam Completed {% else %} {% endif %} {% endfor %} <div class="pass__footer"> <div class="pass-cta" ><a type="button" class="btn buynow btn-block btn--pass btn-primary exams" id="b_{{exam.id}}" style="text-decoration: none; font-size: 15px !important;" href="/quiz/{{exam.url}}" >Start Exam</a> </div> </div> </div> {% endfor %} I would like to display the link "Start Exam" only if the there is no entry in Sitting for that quiz and user. The template successfully displays "Exam Taken" however, I am not able to figure out the else part. Any suggesstions. -
I am using LoginRequiredMixin in Django. If I type the url in search bar it shows the page without being logged in
I am using LoginRequiredMixin in a django class view AdCreateView which is binded to the url /create. When I type the whole url it goes to the page even if I'm logged out but if I click on the create button from anywhere else on the site it redirects to the login page. I would like for it to redirect to the login page in both cases. My urls.py path('', AdListView.as_view(), name='list'), path('create/', AdCreateView.as_view(), name='create'), views.py class AdCreateView(LoginRequiredMixin, View): template_name = 'ads/ad_form.html' success_url = reverse_lazy('ads:list') def get(self, request, pk=None): form = CreateForm() ctx = {'form': form} return render(request, self.template_name, ctx) def post(self, request, pk=None): form = CreateForm(request.POST, request.FILES or None) if not form.is_valid(): ctx = {'form': form} return render(request, self.template_name, ctx) # Add owner to the model before saving pic = form.save(commit=False) pic.owner = self.request.user pic.save() form.save_m2m() return redirect(self.success_url) -
Access form 'fields' in django View class
I am trying to access the 'fields' attribute in my Class based View Here's an example of what my forms.py looks like: from django import forms from .models import ErrorEvent class ErrorEventForm(forms.ModelForm): class Meta: model = HumanErrorEvent # fields = exclude = ['event_id', 'user_modified', 'date_modified'] widgets = { 'owner': forms.TextInput(), } Then here's my views: class ErrorCreateView(CreateView): template_name = "forms/form.html" form_class = ErrorEventForm model = ErrorEvent def get_context_data(self, **kwargs): if not self.request.user.groups.filter(name='leaders').exists(): self.form_class.fields['owner'].widget = forms.HiddenInput() context = super(ErrorCreateView, self).get_context_data(**kwargs) return context The error I am getting is: AttributeError: type object 'ErrorEventForm' has no attribute 'fields' Due to this line: self.form_class.fields['owner'].widget = forms.HiddenInput() Is it not possible to access the 'fields' attribute in the views? If not, is there a way to hide the 'owner' form field based on the group the user is in? Thank you for all your help in advance! -
Django 3 - How to populate HTML Select from Database?
I need to build a Python/Django web app, where the category/subcategory data could run between 100 and 200 rows and will be changing with time. On DJango 3.2.4, I am trying to figure out how can i achieve this? I only have the following link from the DJanago ref: https://docs.djangoproject.com/en/3.2/ref/models/fields/ but it only mentions the topic "Database Representation", without giving any detailed explanation or a concrete example. Perhaps I am missing something here, but would be grateful, if I could be directed to a right resource. -
django model value not geting updated cbv
I am trying to update a profile and I am using Class based views views.py: class ProfileUpdateView(UpdateView): model = User template_name = "users/profile_update.html" success_message = "Your profile was updated successfully" slug_url_kwarg = 'username' slug_field = 'username' context_object_name = 'profile' fields = ['username', 'email'] def get_success_url(self): return reverse_lazy("profile", kwargs={self.slug_url_kwarg:self.kwargs['username']}) If I don't update anything and click on the update button, it redirects me to my profile page.. But if I update, it does not redirect me but rather, it stays is the same page. What am I missing here? profile_update.html: {% extends 'log/base.html' %} {% block content %} {%load crispy_forms_tags %} <div class='container mt-4'> {% if profile.username == user.username %} <form method='POST' autocomplete="off" enctype="multipart/form-data" > {% csrf_token %} <fieldset class='form-group'> <legend class='border-bottom mb-4'>Update Profile</legend> {{ form | crispy }} </fieldset> <div class='form-group'> <button class='btn btn-outline-info' type='submit'>Update</button> </div> </form> {% endif %} </div> {% endblock content %} profile.html : {% extends 'log/base.html' %} {% block content %} {%load crispy_forms_tags %} <title>Error logger - Profile {{ profile.username }}</title> <div id='profile' class="content-section card p-4"> <div class="media"> <img class="rounded-circle account-img" src="{{ profile.profile.avatar.url }}"> <div class="media-body"> <h2 class="account-heading">{{profile.username}} </h2> <p >{{profile.email}}</p> <p>Created on: {{ profile.profile.created }}</p> {% if profile.username == user.username %} <p>Last updated on : … -
use rest_framework_simplejwt with Django 1.11.x and Python 3.6.2
I have an app that is using Django 1.9.2 and python 2.7. Now I wanted to use the simple JWT solution on a REST API and started to upgrade the app to Django 1.11.29 and Python 3.6.2. I cannot upgrade to Django 2.x at a reasonable cost ;-) When I use the url for access token, I am getting correctly my pair of access token and a refresh token back. But when I use refresh token url -X POST \ -H "Content-Type: application/json" \ -d '{"refresh":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImNvbGRfc3R1ZmYiOiLimIMiLCJleHAiOjIzNDU2NywianRpIjoiZGUxMmY0ZTY3MDY4NDI3ODg5ZjE1YWMyNzcwZGEwNTEifQ.aEoAYkSJjoWH1boshQAaTkf8G3yn0kapko6HFRt7Rh4"}' \ http://localhost:8000/api/token/refresh/ I should get back my access token like "access": "eyJ0eXAiOiJ.........." } But I get a response like { "username": [ "this field is required" ], "password": [ "this field is required" ] } I mocked up another super-limited Django app running under Django 2.2.2 and things behave like required. Can anyone help me on this? -
generating paths with django and python, what is the request object
This is my first experience with Django so there's probably an obvious solution I'm not aware of. I have an assignment of creating an encyclopedia-like website, one objective is creating pages for each article that I have. I've created a function in my "views" file: def title_page(request, title): if title not in util.list_entries(): return render(request, "encyclopedia/error.html") return render(request, f"encyclopedia/title.html", { "page_name": title, "content": util.get_entry(title) }) where util.list_entries() is a function that supplies the list of article names and util.get_entry is a function that supplies the content of said article name. in my "urls" file i have a list of url patterns that holds all of my paths: urlpatterns = [ path("", views.index, name="index") ] i tried to create a loop to append a path for each article that i have: for entry in util.list_entries(): urlpatterns.append(path(f"<str:{entry}>", views.title_page(entry), name=entry)) however i get a TypeError: TypeError: title_page() missing 1 required positional argument: 'title' I suppose that title_page function requires the request object but I'm not sure how to access it and how to pass it through the paths function, and moreover in functions like the index function that requires no other positional arguments : def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) … -
Write a django Alluth adapter that checks if a value i unique
Im trying to check if a value for pid is uniqe but i cant manage to make alluth adapter to find the pid field. Any tips? Nothin happend, but if i change pid value to email the code works on the email field. I cant get the pid field to work whit this function. Maybe im referencing it in a wrong way and the filed does not belong to the default account adaptet- class PidMaxAdapter(DefaultAccountAdapter): def clean_pid(self, pid, user): user.profile.pid = pid if len(pid) > 9: raise ValidationError('Please enter a username value\ less than the current one') # For other default validations. return DefaultAccountAdapter.clean_pid(self, pid) -
How to use accessors in Django?
I've read previous Q and docs, however still not able to make it work.. I have the following models: class Process(models.Model): class Meta: verbose_name_plural = "Processes" name = models.CharField(max_length=120) description = models.CharField(max_length=4) parent_process = models.ForeignKey('self', related_name="parent_process+", on_delete=models.PROTECT, blank=True, null=True, verbose_name="parent process") process_activities = models.CharField(max_length = 2048, blank=True, verbose_name="process activites") owner = models.ForeignKey(User, related_name="owner+", on_delete=models.PROTECT, blank=True, null=True, verbose_name="owner") def __str__(self): return "{}".format(self.name) class ControlTest(models.Model): history = AuditlogHistoryField() name = models.CharField(max_length=120) description = models.CharField(max_length=120) Now I want to use an accessor to access the name of the process and display in a table (tables.py): class controltestTable(tables.Table): class Meta: hoofdproces = tables.Column(accessor='process.name') model = ControlTest fields = ['id',"name", "hoofdproces", "sub_process", 'description', 'control', 'delegate', 'owner', 'reviewer1', 'reviewer2', 'reviewer1_r', 'reviewer2_r', 'delegate_r', 'owner_r', 'reviewer_status', 'status', 'history', 'comments', 'review_comments', 'due_date', 'review1_due_date', 'review2_due_date', 'documentation'] template_name = "django_tables2/bootstrap-responsive.html" Views.py: class ControlTestView(SingleTableView, FormView, SingleTableMixin, FilterView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) queryset = kwargs.pop('object_list', None) if queryset is None: self.object_list = self.model.objects.all() context['controltests'] = ControlTest.objects.all() return context def post(self, request, *args, **kwargs): form = self.get_form() print(form) if form.is_valid(): instance = form.save(commit=True) instance.save() print('valid') return self.form_valid(form) else: print(form.errors) return self.form_invalid(form) template_name = "control/ControlTest.html" model = ControlTest form_class = ControlTestForm table_class = controltestTable success_url = reverse_lazy('controltest') However, nothing gets displayed in the … -
Change DateTimeField FORMAT in Django version 3.2.2
I'm trying to change DateTime format for all date time objects in my project. I want to format : 21-06-2021 14:02:12 My settings DATETIME_FORMAT = '%d-%m-%Y %H:%M:%S' TIME_ZONE = 'Africa/Tunis' USE_I18N = True USE_L10N = False USE_TZ = True Result: %21-%06-%2021 %14:%Jun:%st -
Path duplication while saving Django FileField
I have field, that holds audiofile: class Meditation(models.Model): name = models.CharField(max_length=50) audio = models.FileField(upload_to='AudioTracks') length = models.IntegerField(blank=True, null=True) Also I have pre-post signals to convert audio into .m4a and count audio length: @receiver(pre_save, sender=Meditation) def setLengthMeditation(sender, **kwargs): meditation = kwargs['instance'] if kwargs['update_fields']: audio = mp4.MP4(meditation.audio) length = audio.info.length meditation.length = length @receiver(post_save, sender=Meditation) def setLengthToCourse(sender, **kwargs): meditation = kwargs['instance'] if not kwargs['update_fields']: newPath = meditation.audio.name.split('.')[0] + '.m4a' command = 'ffmpeg -i {} -movflags +faststart -b:a 128K -af "afade=t=in:st=0:d=2" {}'.format(meditation.audio.name, newPath) subprocess.call(command, shell=True) meditation.audio = File(open(newPath, 'rb')) meditation.save(update_fields=['audio', 'length']) So, as u can see, when I convert audio from any format to .m4a I try to point new audio to existing model: command = 'ffmpeg -i {} -movflags +faststart -b:a 128K -af "afade=t=in:st=0:d=2" {}'.format(meditation.audio.name, newPath) subprocess.call(command, shell=True) meditation.audio = File(open(newPath, 'rb')) The problem is, when I point model to existing file, Django saves it in "upload_to" and it comes like upload_to {Audiotracks/} + file.name {AudioTracks/file.m4a} = AudioTracks/AudioTracks/file.m4a The question is, can I somehow make Django not make copy of a file OR cut path on saving so no duplication will happen -
How to store dark-mode choice in cookies in Django?
I have the following script NioApp.ModeSwitch = function() { var toggle = $('.dark-switch'); if($body.hasClass('dark-mode')){ toggle.addClass('active'); }else { toggle.removeClass('active'); } toggle.on('click', function(e){ e.preventDefault(); $(this).toggleClass('active'); $body.toggleClass('dark-mode'); }) } Which changes the website to dark-mode, through this toogle <li><a class="dark-switch" href="#"><em class="icon ni ni-moon"></em><span>Modo Nocturno</span></a></li> How can I, in Django, store this in a cookie, so that it remembers the user option? -
Django Forms: Select Widget removes options
I have a model roomTypes which I use as a ForeignKey in Booking class roomType(models.Model): title = models.CharField(max_length=32, default="Single Bed") price = models.DecimalField(default=0, max_digits=5, decimal_places=2) def __str__(self): return self.title class Booking(models.Model): author = models.ForeignKey( "User", on_delete=models.CASCADE, default=None) hotelName = models.CharField(max_length=32, default=None) includeBreakfast = models.BooleanField(default=False,) roomType = models.ForeignKey( 'roomType', default=None, on_delete=models.CASCADE, related_name="roomtypes", widgets={models.Sele}) includeDinner = models.BooleanField(default=False) noOfNights = models.IntegerField(default=1) totalPrice = models.DecimalField( default=0, blank=True, null=True, max_digits=10, decimal_places=2) date = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.author.username} booked a room in {self.hotelName}" when using a modelForm, I used the Select widget to add an id for javascript querySelector use self.fields['roomType'].widget = Select(attrs={ 'id': 'roomType', }) but as I added this, all the options on the form disappear. What do? -
How to filter queryset with one lookup field on mutiple fields in django-filter
Lets say I have 2 fields ["id", "name"]. I want to filter my queryset in my ModelViewSet by using django-filter. Here is my custom FilterSet: from django_filters import rest_framework as filters from store.models import Partner class PartnerFilter(filters.FilterSet): """ Custom Partner Filter Set """ name = filters.CharFilter(field_name="name", lookup_expr="icontains") class Meta: model = Partner fields = ["id", "name"] And This is my ModelViewSet: class PartnerViewSet(ModelViewSet): """ Partner View Set """ serializer_class = PartnerSerializer queryset = Partner.objects.select_related("user").all() permission_classes = [IsAuthenticated,] authentication_classes = [SessionAuthentication] filter_backends = [DjangoFilterBackend,] filterset_class = PartnerFilter What I need is to filter queryset by using only one query string. I don't want my url to be like .../?id=&name=string. I want something like that: .../?search=search_value and if it matches any id then it gets the object by id or if it matches with name then it gets object by name. How can I implement this in django-filter? Is there a way to do it without overriding get_queryset method in ModelViewSet? -
I want to redirect my tinyurl to original url. TinyUrl is generated and rendered successfully, But when i copy and search it on browser, it says Error
I am trying to create short urls for products. The short urls are generated and rendered successfully to the templates, But everytime, it doesnot generate unique short urls, its the same for each product and different for other products. After I got my short URL , i copied it and search it in the browser, It says Server Not Found. I want to redirect those short urls to original urls Below, I am posting functions and urls, please help me get with it. Views.py #Display individual product and render short links for all using pyshorteners def link_view(request, uid): results = AffProduct.objects.get(uid=uid) slink = request.get_full_path() shortener = pyshorteners.Shortener() short_link = shortener.tinyurl.short(slink) return render(request, 'link.html', {"results": results, "short_link": short_link}) Urls.py urlpatterns = [ path('link/', views.link, name='link'), path('link/<int:uid>/', views.link_view, name='link_view') ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Also the address bar in the browser shows: 'affiliation/link/10004/', the localhost has been missed out -
RFID scanner in HTML input field
I'm writing a project on Django and I have the registration template. There I have a field 'RFID' which now can only be filled manually. I need to make this field scan RFID tag automatically right inside that field. When I touch rfid to scanner field in HTML should be filled without typing RFID by hands. If it's possible to do, how I should do it? I've tried to find how to realize it but there is no helpful information across internet. This is my registration form — https://i.stack.imgur.com/17BIn.png -
Form variable for django CreateView
Heads-Up: I don't know if this is a duplicate, but all the questions that StackOverflow said to be similar are not mine. Hi, I have a django model called Post (I am doing the usual 'blog' website, since I am still learning). I am creating a CreateView for it (django.views.generic) to create more posts. My problem is that I want to pass in string as a context variable. This can be done with context_object_name or the function get_context_data. But, to create the form that CreateView automatically generates, it passes a context variable called form. Since I am passing my own context data, the CreateView's form context variable gets overwritten. So, what I am asking is, what is the name of that form variable (if there is) that I can pass into the context data dictionary like {'string': my_string, form: createView_form_variable}. Any help on this would be appreciated - Thanks in advance. P.S. Please comment if I have not made things clear -
Django - NOT NULL constraint failed
I'm currently working on a Django app that will parse the contents of an uploaded log file to the associated database in my Django project. I've managed to get it all running as expected except it won't associate my uploaded data with the model's ForeignKey. I can assign null=True which resolves the integrity error but then of course, it doesn't assign any of the uploaded data to that ForeignKey. Here's the code: models.py class Case(models.Model): case_ref = models.CharField(max_length=8) oic = models.CharField(max_length=50) subject = models.CharField(max_length=100) submitted_date = models.DateTimeField(default=datetime.now, blank=True) def get_absolute_url(self): return reverse('case_list', kwargs={'pk': self.pk}) def __str__(self): return self.case_ref + " " + self.subject class TeamviewerLogs(models.Model): case = models.ForeignKey(Case, on_delete=models.DO_NOTHING) teamviewer_id = models.IntegerField() teamviewer_name = models.TextField() connection_start = models.TextField() connection_end = models.TextField() local_user = models.TextField() connection_type = models.TextField() unique_id = models.TextField() def get_absolute_url(self): return reverse('case_list', kwargs={'pk': self.pk}) def __str__(self): return str(self.teamviewer_id) + " - " + str(self.teamviewer_id) forms.py class UploadLog(forms.ModelForm): file = forms.FileField() class Meta: model = TeamviewerLogs fields = [ 'file' ] views.py def add_logs(request, pk): case = get_object_or_404(Case, pk=pk) if request.method == 'POST': form = UploadLog(request.POST, request.FILES) if form.is_valid(): teamviewer = form.save(commit=False) teamviewer.case = case log_file = request.FILES['file'] log_file = filter(None, (line.rstrip() for line in log_file)) for lines in … -
Django[AJAX] build url from Django Model
Hello friends, I am building a website with Django, I decided to create a filter for my items, you can filter items like this: Item.objects.filter(type=item_type), so basically I created an url which takes a slug:item_type, and returns a JsonResponse with the items parsed as JSON. Then I created an Ajax call in my js file and when I wanted to call the url to filter by type I keep getting an error: function filterItemType(type) { $.ajax({ type: "GET", data: $(this).serialize(), url: "{% url 'boring:filter_items' type%}", ... The Error: Not Found: /boring/{% url 'boring:filter_items' type%} [21/Jun/2021 11:32:54] "GET /boring/%7B%%20url%20'boring:filter_items'%20type%%7D HTTP/1.1" 404 6103 So basically, for my understanding, JS is not parsing the Django {% url .... %}. I have no idea how to do it in order for JS to build the route...like I usually do it in the Templates... PS: I also tried to build the route with the type separated as -> url: "{% url 'boring:filter_items' %}" + "/"+ type; But it's not working either, same error. Github Issue for this matter... -
Redirect a POST request with all the data to a url
Is there a way to redirect on POST request to another URL with all the data. # views.py @verified_email_required def user_page(request, pk, username): if request.method == 'POST': if request.POST.get('_name', '') == 'toggle_pin': auth_profile = Profile.objects.filter(user=request.user).first() profile = Profile.objects.filter(pk=int(request.POST.get('profile', ''))).first() fav = Favourite.objects.filter(profile=auth_profile, pinned_profile=profile).first() if fav.pinned == True: fav.pinned = False else: fav.pinned = True fav.save() return JsonResponse(data={ 'status': fav.pinned, }) # page profile (Profile of the user who's page being is visited) # (also give 404 error if user does not exists) page_user = get_object_or_404(User, pk=pk) if (page_user.username != username): return redirect(f'/u/{page_user.pk}-{page_user.username}/') # page profile page_profile = Profile.objects.filter(user=page_user).first() context = { 'page_profile': page_profile, } return render(request, 'user/profile.html', context) @verified_email_required def redirect_profile_page(request, pk): if request.method == 'POST': # storing the POST data in session is not a good practice # Waht can we do else request.session['_old_post'] = request.POST return redirect(f'/u/{page_user.pk}-{page_user.username}/') page_user = get_object_or_404(User, pk=pk) return redirect(f'/u/{page_user.pk}-{page_user.username}/') In the redirect_profile_page view I redirect users to the user_page view on GET request. How do I do this in a POST request? Any help is highly appreciated! Thank you. -
Django not using updated urls.py - returning 404 on www.site.com/page with outdated list
I am very new to django and beginning to understand some of the framework however view-route binding is confusing me There is a persistent issue that when I try to visit any url except for the homepage and /admin I receive a 404, including routes I have declared in my project's urls.py file also i am following this mdn tutorial project urls.py """trends URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from django.views.generic import RedirectView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('articles/', include('articles.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) app named 'articles' urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] app named 'articles' views.py from django.shortcuts import render from django.http …