Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Like in the comments didn't work and return json page response `{"a_c_like": true}`
I build the comment system and when I click like in the first comment the like appears successfully but when I come to the next comment It returns the JSON response page {"a_c_like": true} instead of like appear and the like count in the span also didn't work (count). I build my comment system on the MPTTModel my view def add_like_to_comment(request, id): comment = Comment.objects.get(id=id) data = {} if request.method == 'POST': account = request.user if comment.likes.filter(id=account.id).exists(): comment.likes.remove(account) a_c_like = False else: comment.likes.add(account) a_c_like = True data["a_c_like"] = a_c_like print(data) return JsonResponse(data) my urls path('comment/like/<int:id>/like', add_like_to_comment, name='add_like_to_comment'), the html template <form method="POST" action="{% url 'video:add_like_to_comment' node.id %}" id="comment-like-form"> {% csrf_token %} <button style="color: #aaaaaa;" class="remove-default-btn p-0 border-0 " type="submit" style="border: none; color: #aaaaaa;" > <svg width="1.5em" height="1.5em" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart" viewBox="0 0 16 16" > <path d="M8 2.748l-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z"/> <span class="ml-1" >{{ node.likes.all.count }}</span></svg> </button> </form> Ajax file which handles the like comments $("#comment-like-form").submit(function(e){ e.preventDefault(); var form = $(this); let url = form.attr("action"); $.ajax({ type: "POST", … -
Showing model data as dropdown list in html Template in Django?
I am trying to access model's data for implementation as dropdown menu but I got stuck in this problem. Can anyone help me?? Here is what i have.... views.py def educationdata(request): obj = DegreeDetails.objects.all() context={ 'Data':obj } return render(request,'Education.html', context) This the view I have created for the model DegreeDetails Model.py class DegreeDetails (models.Model): degree = models.CharField(max_length=10) discipline = models.CharField(max_length= 15) def __str__(self): return '%s %s'%(self.degree, self.discipline) This is the model i am using and this model is used as a ForeignKey in another model as follows, hence i want to show it as dropdown field degree_details = models.ForeignKey(DegreeDetails, on_delete= models.CASCADE) Template.Html <div class="col-lg-8 col-md-8"> <label>Degree Details</label> <input type="text" name="degree_details" id="inputdegree_details" class="form-control" placeholder="Select from Dropdown" value="{{education_form.initial.degree_details}}"> <select class="form-control"> {% for data in Data %} <option>{{data}}</option> {% endfor %} </select> Look forward to your responses, Thank you -
DjangoCMS: Image/picture not showing on the UI
I am using the djangocms for the 1st and I am trying to add an image on the cms page, but it's not showing it's giving a 404 error. Steps performed: pip3 installed djangocms-picture>=2.3,<2.5 In INSTALLED_APPS added 'djangocms_picture' also sets following variables: MEDIA_URL = "/media/" MEDIA_ROOT = '/home/media' CMS_MEDIA_ROOT = MEDIA_ROOT CMS_MEDIA_URL = MEDIA_URL Files get uploaded for the plugins and respected folders too got created but on the CMS UI, it's showing a 404 error. am I missing something or whats steps need to perform more to show an image on the CMS UI. -
AWS S3 bucket returns 403 error when referencing a static folder path in Django project
I'm hosting static files in an S3 bucket for a Django web app. All has been well so far using the Appwork custom admin template: https://uxpowered.com/products/appwork/v160/ The files are rendered fine locally but unable to render from the S3 bucket. I believe the error is the script below that is referencing a folder path instead of a direct file. <script> window.themeSettings = new ThemeSettings({ cssPath: "{% static 'app/admin/assets/vendor/css/rtl' %}", themesPath: "{% static 'app/admin/assets/vendor/css/rtl' %}", }); </script> How can I solve this problem? I confirmed the bucket folder exists and contains the correct files. static files errors -
Django Dependent/Chained Dropdown/Combo List
Cascading not working. When I select Supplier, Services is not working. Nothing is happening. on form load, the "Services" is not empty even though the code is there I am not sure if forms.py is really needed or not. Models.py class supplierMaster(models.Model): # supplierId = models.AutoField(primary_key=True) supplierName = models.CharField(max_length=25) status = models.ForeignKey(statusMaster, on_delete=models.CASCADE) createdOn = models.DateTimeField(auto_now_add=True) def __str__(self): return self.supplierName class servicesMaster(models.Model): # serviceId = models.AutoField(primary_key=True) serviceName = models.CharField(max_length=50) supplierid = models.ForeignKey(supplierMaster, on_delete=models.CASCADE) status = models.ForeignKey(statusMaster, on_delete=models.CASCADE) createdOn = models.DateTimeField(auto_now_add=True) def __str__(self): return self.serviceName class milestonesTran(models.Model): # milestoneid = models.AutoField(primary_key=True) supplierid = models.ForeignKey(supplierMaster, on_delete=models.CASCADE, default=0) serviceid = models.ForeignKey(servicesMaster, on_delete=models.CASCADE, default=0) serviceDate = models.DateTimeField(default=timezone.now) SERVICES_STATUS_CHOICES = [(3, 'Pending'), (4, 'Completed')] servicestatus = models.IntegerField(choices=SERVICES_STATUS_CHOICES, default=3) status = models.ForeignKey(statusMaster, on_delete=models.CASCADE) createdOn = models.DateTimeField(auto_now_add=True) Views.py def add_maintenance(request): services = servicesMaster.objects.all() supplier = supplierMaster.objects.all() servicestatus = statusMaster.objects.filter(pk__in=[3, 4]) status = statusMaster.objects.filter(pk__in=[1, 2]) # print(supplier) return render( request, 'maintenance_add.html', { 'services': services, 'suppliers': supplier, 'servicestatus': servicestatus, 'status': status }) def add_maintenance_save(request): if request.method != "POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: servicedate = request.POST.get("serviceDate") servicename = request.POST.get("servicelist") suppliers = request.POST.get("supplierlist") servicestatus = request.POST.get("servicestatuslist") status = request.POST.get("status") try: milstone = milestonesTran(serviceDate=servicedate, serviceid_id=servicename, supplierid_id=suppliers, servicestatus=servicestatus, status_id=status) milstone.save() messages.success(request, "Maintenance Added Successfully") return HttpResponseRedirect('/servicetracker/add/') except: messages.error(request, "Failed to Add Maintenance") … -
How to update an object and redirect back to home page?
I'm building a website where you can upload photos with name. You can also edit the name and/or the photo after uploading it and I'm having trouble with the edit function. This is my views.py def edit(request, id): photo = Photo.objects.get(id=id) form = PhotoForm(instance=photo) if request.method == 'POST': form = PhotoForm(data=request.POST, instance=photo) if form.is_valid(): form.save() context = { 'obj' : form.instance } # I want it to redirect back to the upload page which i set as '' in urls.py return redirect('/') else: context ={ 'form':form } return render(request, "edit.html", context) This is my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',upload, name='upload_from'), path('edit/<int:id>', edit, name='edit_form'), ] This is my edit.html {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'main.css'%}"> </head> <body> <h2> What do you want to change? </h2> <form id= 'edit_form' action="." method = 'POST' enctype='multipart/form-data'> {% csrf_token %} {{ form.as_p }} <button type = 'submit'> Submit </button> </form> </body> </html> I get an error saying "Page not found" and the http in the browser shows up as: http://127.0.0.1:8000/edit/ I'm assuming is not working because the browser is looking for edit/ with no id, therefore the page is not found, but why is it … -
I want to update a DIV that will contain an image from a database PostgreSQL, without refreshing the entire page. Backend Django
I want to update a DIV that will contain an image, initially there is no image, the image is in a database (the images table will have a field with the image path) PostgreSQL. Every time the database loads an image (it can be at any time) the DIV must be updated, showing the new image, without refreshing the HTML page. If the user wants to see the next image loaded in the database, he will only have to refresh the page. Thank you very much for your support. -
Django Rest frame Work send email from contact form
I am not receiving emails sent from the contact form. I tried it with postman and it's not sending any emails. I just removed the EMAIL_HOST_USER and EMAIL_HOST_PASSWORD detail when I want to post the question. Here is my code: Views.py from .serializers import * from rest_framework.permissions import AllowAny from rest_framework.views import APIView from django.core.mail import send_mail from rest_framework import status from rest_framework.response import Response from contactform.api.serializers import ContactSerailizer class ContactView(APIView): def post(self, request, *args, **kwargs): serailizer_class = ContactSerailizer(data=request.data) if serailizer_class.is_valid(): data = serailizer_class.validated_data w3lName = request.POST('w3lName') w3lSender = request.POST('w3lSender') w3lMessage = request.POST('w3lMessage') send_mail('Contact Form mail from ' + w3lName, w3lMessage, w3lSender, ['test@gmail.com'],) return Response({"success": "Sent"}, status=status.HTTP_200_OK) else: return Response({'success': "Failed"}, status=status.HTTP_400_BAD_REQUEST) Serializers.py from rest_framework import serializers class ContactSerailizer(serializers.Serializer): w3lName = serializers.CharField() w3lSender = serializers.EmailField() w3lMessage = serializers.CharField() Settings #Email config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = True Contact.html <form action="{% url 'contact' %}" method="post" class="signin-form"> {% csrf_token %} <div class="form-input"> <input type="text" name="w3lName" id="w3lName" placeholder="Your name"> </div> <div class="form-input"> <input type="email" name="w3lSender" id="w3lSender" placeholder="Your email address" required=""> </div> <div class="form-input"> <textarea name="w3lMessage" id="w3lMessage" placeholder="Your message" required=""></textarea> </div> <div class="text-right"> <button type="submit" class="btn btn-style btn-primary">Submit</button> </div> </form> -
Getting keyerror when trying to populate HTML via Django Template
I'm making an HTML template that populates a table. The show in value refers to my model, Show, with values title, network, release, and desc. Here is the HTML: {% for key, value in request.session.items %} {% for show in value %} <tr> <td>{{ show.id }}</td> <td>{{ show.title }}</td> <td>{{ show.network }}</td> <td>{{ show.release }}</td> {% endfor %} My request.session looks like this in my views.py: def shows(request): request.session['object_list'] = Show.objects.all() print("*"*500) for key, value in request.session.items(): print(key, value) for show in value: print(show) print("*", show.id) print("*", show.title) print("*", show.network) print("*", show.release) print("*", show.desc) print("*"*500) return render(request, 'shows.html') I can get the code to print in shell, as seen above. But when trying to populate my template, it throws an error: Traceback (most recent call last): File "C:\my_environments\djangoPy3Env\lib\site-packages\django\template\base.py", line 470, in parse compile_func = self.tags[command] KeyError: 'show.id' I'm not sure what base.py -> compile_func = self.tags[command] does. I'm assuming the problem comes from a miscommunication between my template and my views.py, but I can't figure it out. May or may not be important, but the KeyError isn't the only error code thrown. Python states that During handling of the above exception, another exception occured: and goes on to list a … -
set' object is not reversible Django
enter image description here Drive link for full code: https://drive.google.com/drive/folders/15VFgum8aNAgd0PhBpcMRb57AUZ0cWUOg?usp=sharing -
Django form, cascading/dependant dropwdown not submitting correctly
I used this tutorial to have a dependant or cascading dropwdown, which lists the state, county and neighborhood while submitting a form. It displays correctly, but when I hit submit, the following error is listed: "Choose a valid option. That option is not available". It has two apps: posts and location, I'll post the posts.models, posts.forms and templates of posts, but not the view because it is a simple CreateView. About the location app, I'll post the models, views and templates I pass the info to the posts app. I did the location app apart because I want to also use it for searching these posts. ANY advice is extremely appreciated. As a side note: Estado = State, Municipio = County and Colonia = Neighborhood Here's my code: posts.models class PostRoom(models.Model): colonia = models.ForeignKey(Colonia, on_delete=models.SET_NULL, blank=True, null=True) municipio = models.ForeignKey(Municipio, on_delete=models.SET_NULL, blank=True, null=True) estado = models.ForeignKey(Estado, on_delete=models.SET_NULL, blank=True, null=True) class PostPerson(models.Model): colonia = models.ForeignKey(Colonia, on_delete=models.SET_NULL, blank=True, null=True) municipio = models.ForeignKey(Municipio, on_delete=models.SET_NULL, blank=True, null=True) estado = models.ForeignKey(Estado, on_delete=models.SET_NULL, blank=True, null=True) posts.forms class PostPersonForm(forms.ModelForm): class Meta: model = PostPerson fields = ('colonia', 'municipio', 'estado') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['municipio'].queryset = Municipio.objects.none() self.fields['colonia'].queryset = Colonia.objects.none() class PostRoomForm(forms.ModelForm): class Meta: model = … -
Django Toggle Div on Search Query
I have a basic search query to find customers on one of my forms in my Django project. It returns results from the database in an HTML table. The query is executed by clicking the search button. I want to hide the div encapsulating the table when the query has not been executed. Because the JS function is executed when the search button is clicked, the table only shows momentarily until the page reloads. What is the convention for displaying a div after a query is executed, without having a constant toggle button? views.py @method_decorator(login_required, name='dispatch') class CustomerResultsView(ListView): model = CustomerName template_name = 'parent/child.html' context_object_name = 'filtered_customers' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['form1'] = FilterForm(initial={ 'name': self.request.GET.get('name', ''), 'filter_field': self.request.GET.get('filter_field', '') }) context['users'] = self.request.user context['form'] = Customer() return context def get_queryset(self): query = self.request.GET.get('name') filter_field = self.request.GET.get('filter_field') if query: return CustomerName.objects.filter( Q(('%s__icontains' % filter_field, query)) ) else: return {} child.html <form method="GET"> <legend class="border-bottom mb-4">Customer Lookup</legend> <fieldset class="form-group"> {{ form1|crispy }} </fieldset> <div class="form-group"> <input type="submit" class="btn btn-outline-info mt-4" value="Search" onclick="showDiv"> </div> </form> <hr> <div class="table-responsive" id="custTabDiv" style="display:none"> <table id="testTable" class="table table-striped table-hover" cellspacing="0" width="100%"> <thead> <tr> <th … -
Why is this Django DivErrorList being escaped?
I created a DivErrorList class as in these instructions or this stackoverflow answer. To repeat: from django.forms.utils import ErrorList class DivErrorList(ErrorList): def __str__(self): return self.as_divs() def as_divs(self): if not self: return '' return '<div class="errorlist">%s</div>' % ''.join(['<div class="error">%s</div>' % e for e in self]) When I use the class as an error_class in a form, I get escaped text. So instead of divs in my page, I get text saying <div class="errorlist">.... I had to add mark_safe to as_divs to get it to work. Is there a reason the example does not have mark_safe, but I need to add it to make it work? Is there some context I'm missing about what is escaped and what isn't? -
Django from github to PC without requirements.txt
wanted to ask if it is possible and if it worth to try to run a cloned Django repo which doesn't have a requirements.txt file ThankYou! -
Initializing Django model field with the model field from the same Model temporarily
I am building a trip reservation app in Django 2.1 and have some problem with updating available seats in the car for the trip. Your help would be greatly appreciated) Here below, I have my first model, I am trying to initialize available_seats with seats just for the first time when the model will be created. First, I tried below method class Trip(models.Model): origin = models.CharField(max_length=120) destination = models.CharField(max_length=120) time_date = models.DateTimeField(auto_now=True) arrival_time = models.DateTimeField() trip_cost = models.IntegerField() vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) seats = models.IntegerField() available_seats = models.IntegerField(default=seats) yes, this method doesn't work because it is not possible to assign a variable to the one which is not defined yet. Thus, I come with solutions that I need to rewrite the save() method of the model or use signals to accomplish what i want. So, I did: class Trip(models.Model): origin = models.CharField(max_length=120) destination = models.CharField(max_length=120) time_date = models.DateTimeField(auto_now=True) arrival_time = models.DateTimeField() trip_cost = models.IntegerField() vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) seats = models.IntegerField() available_seats = models.IntegerField() #rewriting save() method # def save(self, created=False, *args, **kwargs): # if created: # self.available_seats = self.seats # super().save(*args, **kwargs) #using signals @receiver(pre_save, sender=Trip) def default_available_seats(sender, instance=Trip, created, **kwargs): if created: instance.available_seats = instance.seats These two ways … -
Como autocompletar campos (lat, long) en un modelo con la api geocode?
Tengo un dilema, quiero autocompletar los campos (latitud y longitud) con la peticion a la api geocode cuando genero un post a un modelo con los datos de que se suministran manualmente (ciudad y direccion). este es mi modelo class Comprador(models.Model): usuario = models.ForeignKey(User, on_delete=models.CASCADE) nombre = models.CharField(verbose_name="Nombre", max_length=50) apellido = models.CharField(verbose_name="Apellido", max_length=50) direccion = models.CharField(verbose_name="Dirección", max_length=50) ciudad = models.CharField(verbose_name="Ciudad", max_length=50) longitud = models.DecimalField(verbose_name="Longitud", max_digits=20, decimal_places=2, null=True, blank=True, default=0.00) latitud = models.DecimalField(verbose_name="Latitud", max_digits=20, decimal_places=2, null=True, blank=True, default=0.00) mi view: def post(self, request): serializer = CompradorSerializer(data=request.data, many=True) address = request.data[0]["direccion"] city = request.data[0]["ciudad"] api_response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address='+address.replace(" ","+"),city+'&key=AIzaSyDlmeg0VOQzbGnYDlYaRapYCG6w_DmnB54') api_response_dict = api_response.json() if api_response_dict['status'] == 'OK': latitud = api_response_dict['results'][0]['geometry']['location']['lat'] longitud = api_response_dict['results'][0]['geometry']['location']['lng'] print(latitud, longitud) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return HttpResponse('OK') como lat y long pueden ir vacios quiero que con direccion y ciudad y la peticion de geocode en el post me autocomplete estos campos. Agradeceria su colaboracion. Gracias!! -
NameError: name '*field*__range' is not defined
I'm attempting to filter a QuerySet within a certain date range with the __range lookup field. However, the following error is being raised: NameError: name 'posted__range' is not defined. Upon checking the model instance in the QuerySet, it in fact does have a value assigned to the posted field. I cannot debug it any further so it leaves me puzzled as to why that NameError is being raised in this context? class TestTopicListMainPage__002(TestCase): '''Verify that a topic and associated information is displayed on the main page once the topic is created''' @classmethod def setUpTestData(cls): user = User.objects.create_user("TestUser") python_tag = Tag.objects.create(name="Python") js_tag = Tag.objects.create(name="JavaScript") content = { 'heading': "Test Title", 'text': "Mock text content", 'posted': datetime.datetime.now() } cls.topic = Topic(**content) cls.topic.author = user cls.topic.save() cls.topic.tags.add(python_tag, js_tag) def test_topics_main_page_rendered_topics(self): print(self.topic.posted) response = self.client.get( reverse("topics:listing") ) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "topics/listing.html") self.assertContains(response, "Test Title") self.assertContains(response, "Python") self.assertContain(response, "JavaScript") self.assertContains(response, "TestUser") > \topics\views.py(63)get() -> if topics: (Pdb) topics <QuerySet [<Topic: Test Title>]> (Pdb) topics.count() 1 (Pdb) topics[0].posted datetime.date(2021, 3, 15) (Pdb) n > topics\views.py(64)get() -> topics = topics.filter(posted__range(previous_days, now)) (Pdb) n NameError: name 'posted__range' is not defined class AbstractListingView(TemplateView): template_name = "topics/listing.html" def get_context_data(self): context = super().get_context_data() context['topics'] = Topic.objects.all() return context class TopicsMainPage(AbstractListingView): template_name … -
How to build a backend for an iOS app with swift 5
I want to build an ios app but i am not sure how to build the backend of the app. Do i have to build an api? I have some experience in django and I have seen some people use the Django rest framework. But i am still not sure on how to do this. If some of you know how to build a backend for an ios app please let me know what I need to learn in order to do so. Also, if possible, are there any good resources that are useful for doing this? -
django update view not showing date input (previous) values
when I go to the update page, all previous values are shown except date inputs (deadline and reminder). how can I fix it? At first I didnt use TaskCreationForm for TaskUpdateView considering django will handle it automatically, but then the date inputs became normal text inputs and therefore no datepicker would appear when clicking on the textbox. I thought it was for the widgets that I had used so I decided to use TaskCreationForm for both creation and update. models.py class Task(models.Model): deadline_date = models.DateTimeField(verbose_name='Deadline') status = models.BooleanField(verbose_name='Task Status', default=False) reminder = models.DateTimeField(verbose_name='reminder') class Meta: verbose_name_plural = 'Tasks' ordering = ('-deadline_date',) db_table = 'task' forms.py class DateInput(forms.DateInput): input_type = 'datetime-local' class TaskCreationForm(forms.ModelForm): class Meta: model = Task fields = ('title', 'deadline_date', 'description', 'reminder') labels = { 'reminder': 'remind me' } widgets = { 'deadline_date': DateInput(), 'reminder': DateInput(), 'description': forms.Textarea(attrs={'cols': 80, 'rows': 5}) } views.py class TaskCreateView(CreateView): model = Task form_class = TaskCreationForm template_name = 'mysite/add_task.html' success_url = reverse_lazy('mysite:home') def post(self, request, *args, **kwargs): task_form = TaskCreationForm(request.POST) if task_form.is_valid(): cd = task_form.cleaned_data current_user = request.user task = Task(title=cd['title'], description=cd['description'], user=current_user, deadline_date=cd['deadline_date'], reminder=cd['reminder'] ) task.save() return redirect('mysite:home') class TaskUpdateView(UpdateView): model = Task form_class = TaskCreationForm # fields = ('title', 'deadline_date', 'reminder', 'status', … -
bulk add object for many to many fields for existing objects
Models here. class Book(models.Model): title = models.CharField(max_length=100) author = models.ManyToManyField(null=true, blank=true) class Author(models.CustomUser): # some fields And some instance. Book1: {author: 1, author:2} Book2: {author: 2, author:3} I want to add author 4 to all books. Books.objects.bulk_update(????) , expect the result below: Book1: {author: 1, author:2, author:4} Book2: {author: 2, author:3, author:4} ... ... ... Book100: {author: ****, author:4} -
How to handle error function in python / django
I am new in python and django, right now I am trying to develop face recognition api and I get error, here is the error log: https://gist.github.com/wahyu-handayani/9d8338741ee50697332f7ed63f9769e2 when that error happens, the server will off so I just want to throw or return something in postman, so that the server will still on. So far I have been doing try and except try: # some codes cv2.imshow('Frame', image) # here is the code that makes the error happens except Exception as e: return JsonResponse({"Error": str(e)}) but still.. it does't go to Exception block. How to do the right way for try and except in a function ? -
Empty Queryset upon requesting TemplateView
I'm creating a page where if no model instances have been created, placeholder text is inserted into the page to give the user that no topics exist. If model instances do exist, they are rendered in a manner similar to the Stack Overflow main page. Upon testing (and debugging) the view, an empty QuerySet is returned instead of returning a QuerySet with the one model instance created in the TestCase. What is missing for the QuerySet to not populate with the instance. I'm familiarizing myself with CBVs, thus the reason I'm using a TemplateView > \topics\views.py(49)get() -> context = self.get_context_data() (Pdb) n > \topics\views.py(50)get() -> if not query: (Pdb) context {'view': <topics.views.TopicsMainPage object at 0x000001BE71677A48>, 'topics': <QuerySet []>, 'login_form': <UserLoginForm bound=False, valid=Unknown, fields=(username;password)>, 'search_form': <SearchForm bound=False, valid=Unknown, fields=(search)>} tests.py class TestTopicListMainPage__002(TestCase): '''Verify that a topic and associated information is displayed on the main page once the topic is created''' @classmethod def setUpTestData(cls): user = User.objects.create_user("TestUser") python_tag = Tag.objects.create(name="Python") js_tag = Tag.objects.create(name="JavaScript") content = { 'heading': "Test Title", 'text': "Mock text content" } cls.topic = Topic(**content) cls.topic.author = user cls.topic.save() cls.topic.tags.add(python_tag, js_tag) def test_topics_main_page_rendered_topics(self): response = self.client.get( reverse("topics:listing") ) self.assertequal(response.status_code, 200) self.assertTemplateUsed("topics/listing.html") self.assertContains(response, "Test Title") self.assertContains(response, "Python") self.assertContain(response, "JavaScript") self.assertContains("TestUser") views.py … -
Can't run Celery task in Django - I either get "AppRegistryNotReady: Apps aren't loaded yet" or "RuntimeError: populate() isn't reentrant"
I'm trying to setup a task with Celery in Django to run every day at 23:00. app = Celery('App.tasks', broker='redis://localhost') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "App.settings") django.setup() <== PROBLEM @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task( crontab(hour=23), calc_average_rating.s(), ) @app.task def calc_average_rating(final_content_id): The problem is that in this function, I have Rating = apps.get_model(app_label='App', model_name='Rating'), and If I don't call django.setup() then I get django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.. However, If I call django.setup(), the tasks are running fine but I can't do manage.py runserver as I get RuntimeError: populate() isn't reentrant. Any solutions? -
How to delete all migration files in Django app
I'm trying to delete all migration files in my Django app using a single command. Here's the structure of my repository: |-- core | |-- migrations | |-- __init__.py | |-- 0001_initial.py | |-- 0002_add_column1.py | |-- 0003_add_column1.py | |-- users |-- migrations |-- __init__.py |-- 0001_initial.py |-- 0002_add_column2.py My goal is to delete all files besides __init__.py so the repo looks like this: |-- core | |-- migrations | |-- __init__.py | |-- users |-- migrations |-- __init__.py I've tried the following command but no luck: find . -path "*/migrations/*.py" -not -name "__init__.py" -delete -
django singup & log in on index page doesnt work
This is my first time to extend User with AbstractBaseUser. However, I have a problem when I try to signup/login from the index page. Before I implement login I was able to signup without a problem and redirected to the dashboard, as well a message will show up that I'm signup. Now I can't signup neither login. I'm not sure what could be the problem. I will appreciated any help to solve this. Thank you. forms: class ProfileForm(ModelForm): class Meta: model = Profile exclude = ('user',) class SignUpForm(UserCreationForm): class Meta: model = User fields = ('username','full_name','email','password1','password2',) labels = { 'email' : 'Email address', } view: def index(request): # SIGN UP form = SignUpForm() login_form = AuthenticationForm() if request.method == "POST": if request.POST.get('submit') == 'sign_in': form = SignUpForm(request.POST) if form.is_valid(): form.save(); messages.success(request, "Successfully registered.") return redirect("dashboard") elif request.POST.get('submit') == 'sign_up': # LOGIN login_form = AuthenticationForm(data = request.POST) if login_form.is_valid(): email = login_form.cleaned_data.get('email') password = login_form.cleaned_data.get('password') user = authenticate(email=email, password=password) if user is not None: login(request, user) messages.success(request, "Successfully logged in.") return redirect('dashboard') return render(request, 'index.html', context={'form':form,'login_form':login_form}) _header.html: <div class="logout"> {% if user.is_authenticated %} <!-- LOGGED IN --> <!-- MENU --> <div class="profile-menu-dropdown hide"> <a href = "">Profile</a> <a href = "">Edit …