Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The error was: <lambda>() missing 1 required positional argument: 'collation'
when i try to run: python manage.py inspectdb > models.py this error occur in tha models.py , the database is mssql -
for loop in html template and saving values in a variable
i have a html template where i am sending a list(array) from my python file. now i am running a loop in html file and its showing the list perfectly but i want to save every element in a global variable of html and then use this variable. my code is: ''' {%for i in title_list%} {{i}} <br> <br> {%endfor%} ''' here title_list is the list and i want to save the variable i in a new declared variable. how to declare a variable in html and store such type of value in it? -
How to add email and name fields into SendMail upon user creation in Django
I made a signal that triggers SendMail when I create a user. Only superusers can create users from the Admin site, the users can't register themselves. This is important form me. So the signal works well and when I create a new user it sends the email. My problem is that in the Django Admin when I create a user I am not able to add the email address and first and last name until I save the user. But when I save it sends the mail without the mentioned fields because that moment those are blank. How can I do that the signal wait for the second saving or modifying when I fill the email and name fields? models.py class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) ... """I extended the User model with a Profile""" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() """and here is the mail sending signal""" @receiver(post_save, sender=User) def send_new_user_data_email(sender, instance, created, **kwargs): # if a new user is created, compose and send the email if created: username = instance.username subject = 'Subject line' message = 'User: … -
Integrating Selenium Bot into Django
I have a chatbot that I made with selenium. This chatbot should work on multiple users. At the same time, I need to pull and push data from the chatbot. And I want users to be able to command the bot whenever they want. Closing the bot, Writing a message, etc. When the button is pressed from the panel, I want to raise the bot to its feet. I thought of many ways to do this. Django Celery build, Heroku, Docker Container or Aws Lambda Container . With which platform can I ensure that the bot works perfectly, that the communication takes place and that the cost is the least? Do you have a previous source? -
Django - [Errno 2] No such file or directory for Img.open(`image_path`)
I have a blog where users can upload and edit posts. I wanted to resize any uploaded image to a max. of 500*500px. For this purpose I created an if statement before save models.py def _upload_path(instance, filename): return instance.get_upload_path(filename) class Post(models.Model, HitCountMixin): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) image = models.ImageField(blank=True, null=True, upload_to=_upload_path) def __str__(self): return self.title def get_upload_path(self, filename): return "posts/images/" + str(self.user.username) + "/" + filename def save(self, *args, **kwargs): # resize image if self.image: img = Image.open(self.image.path) # Open image using self if img.height > 500 or img.width > 500: new_img = (500, 500) img.thumbnail(new_img) img.save(self.image.path) # saving image at the same path return super(Post, self).save(*args, **kwargs) Unforunalty the image path gets not recognized and I get an error [Errno 2] No such file or directory: '/Users/vic/Desktop/django_project/media/postimage1.jpg' This path is wrong! The upload-path is defined within the get_upload_path() function and should lead to /Users/vic/Desktop/django_project/media/posts/images/username/postimage1.jpg I tried to change the open path to img = Image.open(str(settings.MEDIA_URL) + self.get_upload_path(self.image.name)) or to hardcoded URL with localhost:8000... but nothing worked. If I remove the if statement the file gets uploaded in the correct path so the error must be at img definition. -
Returning error None Django html responding?
I am trying to make a to-do app in Django, Whenever I input a date in either string or Date, then it returns none to the todo list app model.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Task(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) deadline = models.CharField(max_length=200) def __str__(self): return f'{self.title} {self.deadline}' class Meta: order_with_respect_to = 'user' task_list.html {% extends 'base/main.html' %} {% block content %} <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script> <div class="header-bar"> <div> <h1>Hello {{request.user|title}}</h1> <h3 style="margin:0">You have <i>{{count}}</i> incomplete task{{ count|pluralize:"s" }}</h3> </div> {% if request.user.is_authenticated %} <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} </div> <div id="search-add-wrapper"> <form method="GET" style="display: flex;"> <input type='text' name='search-area' placeholder="Search your task" value="{{search_input}}"> <input class="button" type="submit" value='Search'> </form> {% if tasks|length > 0 %} <a id="add-link" href="{% url 'task-create' %}">&#x2b;</a> {% endif %} </div> <!-- Hidden form. Form submits new item positions --> <form style="display: none;" id="reorderForm" method="post" action="{% url 'task-reorder' %}"> {% csrf_token %} <input type="hidden" id="positionInput" name="position"> </form> <div id="tasklist" class="task-items-wrapper"> {% for task in tasks %} <div class="task-wrapper" data-position="{{task.pk}}"> <div class="task-title"> {% if … -
DRF DateField - error when saving form: Date has wrong format. Use one of these formats instead: YYYY-MM-DD
I'm POSTing a form to my Django Rest Framework backend. There is a DateField I am using which is optional depending on the form type the user is looking at. When the user can see the DateField and select the date, it submits appropriately and there are no issues. When the DateField is hidden, I am getting a formatting error when I submit the form (but shouldn't) The form renders the elements appropriately via HTML: When the date is VISIBLE: <div class="mt-2 text-center"> <input type="hidden" name="summative" value="127" id="id_summative"> <input type="hidden" name="evaluation_type" value="31" id="id_evaluation_type"> <div id="id_evaluation_levelFormGroup" class="form-group"> <label class="form-label" for="id_evaluation_level">Evaluation level</label> <select name="evaluation_level" class="form-control" required="" id="id_evaluation_level"> <option value="" selected="">---------</option> <option value="41">Formal</option> <option value="42">Informal</option> </select> </div> <div id="id_evaluation_dateFormGroup" class="form-group"> <label class="form-label" for="id_evaluation_date">Evaluation date</label> <input type="date" name="evaluation_date" value="2021-09-08" class="form-control" id="id_evaluation_date"> </div> </div> When HIDDEN: <div class="mt-2 text-center"> <input type="hidden" name="summative" value="127" id="id_summative"> <input type="hidden" name="evaluation_type" value="33" id="id_evaluation_type"> <input type="hidden" name="evaluation_level" value="43" id="id_evaluation_level"> <input type="hidden" name="evaluation_date" id="id_evaluation_date"> </div> The evaluation_date is not a required field, the model attribute looks like this: evaluation_date = models.DateField( auto_now=False, auto_now_add=False, null=True, blank=True ) My Serializer looks like this (includes the validation method for the date): class EvaluationSerializer(serializers.ModelSerializer): def validate_evaluation_date(self, attrs): # Get the date string date_string = self.context["request"].data["evaluation_date"] … -
Why isn't my ChoiceField rendering from my Django form onto the template?
I'm using django forms and trying to render the name of the form object stored in the dictionary key and its corresponding value stores a form.ChoiceField to display on the website. For some reason, it is only displaying the object location in memory e.g. <django.forms.fields.ChoiceField object at 0x04B304D8> rather than the dropdown itself. These dropdowns are just a selection from 0 up to N where N is the quantity of the item available in the database. Here is my Form Code name = forms.CharField(label="Employee Name", max_length = 200, required = False) jobsite = forms.CharField(label="Jobsite", max_length = 200, required = True) date_needed = forms.DateField(initial = now, required = True) SundryFields = {} def __init__(self, *args, **kwargs): sundries = kwargs.pop('sundries') super(CreateNewOrder, self).__init__(*args, **kwargs) # ? it works i guess ? for sundry in sundries: quantity_list = [(i, i) for i in range(sundry.quantity_available + 1)] self.SundryFields[sundry.name] = forms.ChoiceField(choices=quantity_list) Here is my View ```def orders(response): if response.method == "POST": form = CreateNewOrder(response.POST, sundries = Sundry.objects.all()) # holds information from form if form.is_valid(): cleaned_data = form.cleaned_data order = Order(name=cleaned_data["name"], jobsite=cleaned_data["jobsite"], date_needed=cleaned_data["date_needed"]) order.save() # delete these from the order -- no longer needed once an order object is created del cleaned_data["name"] del cleaned_data["jobsite"] del cleaned_data["date_needed"] # … -
Pybars does not compile jinja if condition and for loop
I am using saleor platform on a project. Im trying the compile emails having jinja templates syntax using pybars. But the pybars is not parsing the if condition and the for loop syntax. Please guide me on parsing this two. Thanks! context = { "site_name": "site_name", "order": { "items": [ "one", "two", "three", ] }, } source = """ {% if True %} <div> {{ site_name}} </div> {% endif %} <div> {% for line in order.items %} <tr> {{ line }} </tr> {% endfor %} </div> <div> <p><small>This email was sent to <a href="mailto:{{site_name}}">{{site_name}}</a>.</p> </div> """ from pybars import Compiler compiler = Compiler() template = compiler.compile(source) template(context) Output that i am getting is as below. '\n {% if True %}\n <div>\n site_name\n </div>\n {% endif %}\n\n\n <div>\n {% for line in order.items %}\n <tr>\n \n </tr>\n {% endfor %}\n </div>\n\n <div>\n\n <p><small>This email was sent to <a href="mailto:site_name">site_name</a>.</p>\n\n </div>\n\n' -
ModuleNotFoundError: No module named 'typing_extensions'
i am working in a blog site with django. my project urls.py code: from django.contrib import admin from django.urls import path from.import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name="home"), path('login/',views.authlogin,name="login"), path('signup/',views.signup,name="signup"), path('contact/',views.contact,name="contact"), path('about/',views.about,name="about"), path('logout/',views.authlogout,name='logout'), path('dashboard/',views.dashboard,name='dashboard'), path('updatepost/<int:id>',views.update_post,name='updatepost'), path('addpost/',views.add_post,name='addpost'), path('delete/<int:id>',views.delete_post,name='deletepost'), ] but it shows me File "C:\Users\ABU RAYHAN\Desktop\projects\miniblog\blog\urls.py", line 3, in <module> from.import views File "C:\Users\ABU RAYHAN\Desktop\projects\miniblog\blog\views.py", line 1, in <module> from typing_extensions import Required ModuleNotFoundError: No module named 'typing_extensions' i am new here pardon my mistake. -
I need to extract data from database using ajax in django
I need to extract data from the database and view the results on a chart in the view, the charts should change dynamically when the values in the database change(the model is done to get the data of users after submitting a survey Here is my model. class Survey(models.Model): gender=models.CharField(max_length=200) Age = models.CharField(max_length=200) Nationality=models.CharField(max_length=200) Gorvernate = models.CharField(max_length=200) Maritalstatus=models.CharField(max_length=200) Employmentstatus=models.CharField(max_length=200) children=models.CharField(max_length=200) Education =models.CharField(max_length=200) IncomePerMonth=models.CharField(max_length=200) class Meta: db_table = 'form_surey' I tried this in the view: <script> $.ajax({ type: 'GET', url: "{% url 'pie-chart' %}", data: {{gender}}, success: function (response) { // if not valid user, alert the user if(!response["valid"]){ alert("Success"); } }, error: function (response) { console.log(response) } }); const labels = ['Male','Female']; const data = { labels: labels, datasets: [{ label: 'Gender', backgroundColor: ['rgb(255, 99, 132)', 'rgb(54, 162, 235)', ], borderColor:[ 'rgb(255, 99, 132)', 'rgb(54, 162, 235)', ], data: {{gender|safe}}, }] }; const config = { type: 'bar', data: data, options: {} }; // === include 'setup' then 'config' above === var myChart = new Chart( document.getElementById('myChart'), config ); </script> -
I'm using Django ImageField but I can't access the images in my posts.html page
I'm using ImageField in Django but when I try to access them in my html pages, it's not working. Here is my model: class Post(models.Model): headline = models.CharField(max_length=200) sub_headline = models.CharField(max_length=200, null=True, blank=True) thumbnail = models.ImageField(null=True, blank=True, upload_to="images", default="placeholder.png") body = models.TextField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) featured = models.BooleanField(default=False) tags = models.ManyToManyField(Tag, null=True) Here is how am trying to access the images in posts.views {% for post in posts %} <div> <div class="post"> <img class="thumbnail" src="{{post.thumbnail.url}}"> <div class="post-preview"> <h6 class="post-title">{{post.headline}}</h6> <p class="post-intro">{{post.sub_headline}}</p> <a href="{% url 'post' post.id %}">Read More</a> <hr> {% for tag in post.tags.all %} <span class="tag">{{tag}}, </span> {% endfor %} </div> </div> </div> {% empty %} <h3 align="center">No posts found...</h3> {% endfor %} For more information: views.py def posts(request): posts = Post.objects.filter(active=True) context = {'posts': posts} return render(request, 'base/posts.html', context) urls.py urlpatterns = [ path('', views.home, name="home"), path('posts/', views.posts, name='posts'), ] posts.html {% extends 'base/main.html' %} {% load static %} {% block content %} <div class="main-container"> <h3 align="center">Posts</h3> <div class="post-wrapper"> {% for post in posts %} <div> <div class="post"> <img class="thumbnail" src="{{post.thumbnail.url}}"> <div class="post-preview"> <h6 class="post-title">{{post.headline}}</h6> <p class="post-intro">{{post.sub_headline}}</p> <a href="{% url 'post' post.id %}">Read More</a> <hr> {% for tag in post.tags.all %} <span class="tag">{{tag}}, </span> … -
Return Nonze for Date Django submit
I am trying to make a to-do app in Django, Whenever I input a date in either string or Date, then it returns none to the todo list app model.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Task(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) deadline = models.CharField(max_length=200) def __str__(self): return f'{self.title} {self.deadline}' class Meta: order_with_respect_to = 'user' task_list.html {% extends 'base/main.html' %} {% block content %} <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script> <div class="header-bar"> <div> <h1>Hello {{request.user|title}}</h1> <h3 style="margin:0">You have <i>{{count}}</i> incomplete task{{ count|pluralize:"s" }}</h3> </div> {% if request.user.is_authenticated %} <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} </div> <div id="search-add-wrapper"> <form method="GET" style="display: flex;"> <input type='text' name='search-area' placeholder="Search your task" value="{{search_input}}"> <input class="button" type="submit" value='Search'> </form> {% if tasks|length > 0 %} <a id="add-link" href="{% url 'task-create' %}">&#x2b;</a> {% endif %} </div> <!-- Hidden form. Form submits new item positions --> <form style="display: none;" id="reorderForm" method="post" action="{% url 'task-reorder' %}"> {% csrf_token %} <input type="hidden" id="positionInput" name="position"> </form> <div id="tasklist" class="task-items-wrapper"> {% for task in tasks %} <div class="task-wrapper" data-position="{{task.pk}}"> <div class="task-title"> {% if … -
Crispy form don't look so pretty in django with bootstrap4?
i create a sell template in a good way , with just div class container and simple row with just a shadown, in column i add {{form|crispy}} of caulse i add {% load crispy_forms_tags %} tag, and again add CRISPY_TEMPLATE_PACK = 'bootstrap4' to setting, yeah i use bootstrap 4. the problem the form crispy not range good, look the photo so please help me! this my sell template {% extends 'base.html' %} {% load crispy_forms_tags %} {% load static %} {% block title%}{% endblock%} {% block content %} <!--container --> <div class="container"> <!-- row --> <div class="row"> <!-- column --> <div class="col-lg-2"> </div> <!-- end column --> <!-- column --> <div class="col-lg-8 shadow p-3 mb-5 bg-white rounded"> <div class="text-center" style="margin-bottom: 2em;"> <h3>Star sell your product</h3> <p>Using color to add meaning only provides a visual indication, which will not be conveyed to users of assistive technologies</p> </div> <form action="/publish/" class ="put" method="post" enctype="multipart/form-data">{% csrf_token %} <div class="form-group "> {{ form.media }} {{ form|crispy}} <h5 class="m-2"> Add More Images</h5> </div> <button type="submit" class="site-btn">Next</button> </form> </div> <!-- end column --> <!-- column --> <div class="col-lg-2"> </div> <!-- end column --> </div> <!-- end row --> </div> <!-- end container --> {% endblock %} -
Django - error while saving an object in `TabularInline` while the primary key is a string and is readonly
I have the following models: class Parent(models.Model): name = models.CharField(max_length=255) class Child(models.Model): id = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) The Child model has a primary key (ID) of type string. Now I'm trying to display the children in a TabularInline inline inside the Parent admin form and I want the ID field to be readonly: class ChildMemberLinkAdmin(admin.TabularInline): model = Child extra = 0 fields = ("id", "name") readonly_fields = ("id",) @admin.register(Parent) class ParentAdmin(admin.ModelAdmin): fields = ("name",) inlines = (ChildMemberLinkAdmin,) I created a parent and a child in Django Shell, and verified each has an ID and name. They're displayed correctly in Django Admin. However, when I click the Save button in the Parent form (even without changing anything) I get an error "Please correct the errors below.". When I debugged it I noticed that child's id is somehow missing, which is weird because my Child instance already has an ID which is displayed as readonly in the TabularInline in the form. When I remove id from the ChildMemberLinkAdmin.readonly_fields everything works correctly. Any idea how to fix this? I'm using the latest Django version: 3.2 -
Filter booked appointments by business working hour
Business working hours(TimeField) are stored for everyday in UTC time. BusinessHours table business = models.ForeignKey(Business) day = models.CharField(max_length=10) opening_time = models.TimeField() closing_time = models.TimeField() Appointment table appointment_time = models.DateTimeField() I'm trying to get particular day's appointments for the stored business hours range(between opening_time and closing_time). Here is the query appointments = models.Appointments.objects.filter(service_start_time__week_day=3, service_start_time__gte=datetime.utcnow(), service_start_time__time__range=(day_obj.opening_time, day_obj.closing_time)) Sometimes the closing_time may be greater than the opening_time. Above query is not getting the records due to this reason. For 03:00(opening) Indian standard Time to UTC is 22:30 and 20:00(closing) corresponding UTC is 14:30. In this case closing time seems greater than closing time. Query doesn't filter anything even though appointments available. How to solve this problem? -
Create a django program where data is input in a form, a python code creates a graph using the data, and the graph is displayed beneath the same form
I'm very new to Django and wish to write a program that does the following. The user gives inputs into a form. On clicking submit a graph is displayed underneath the form (the user must not be redirected to a different page). This graph must be created by a python code using the inputs that were originally submitted in the form. So far I've been able to make a program where the graph is created and displayed in a different html page. But I want it to be displayed in the same page underneath the form. I'm using matplotlib to make the graph. The graph is saved as a png image. Is there some way to go about this using only django? Thanking all responses in advance. -
Django JS autocomplete with Materialize
I'm trying to get the Materialize autocomplete function to work with a django. But for some reason the content won't show I did allot of debugging but I can't seem to find why it is not working and showing the options. Im using the following view: def search_companies(request): """ Search for relations on company names basis. """ companies = Relation.objects.all() data = [] for company in companies: data.append(company.company_name) return JsonResponse({'data': data}) And the following JavaScript in the template function autocompleted(){ fetch('/orders/search_companies/') .then(response => response.json()) .then(data => { var my_data = data.data; let myConvertedData = {}; $.each(my_data, function (index, value) { myConvertedData[value] = null; }); document.addEventListener('DOMContentLoaded', function () { const inputField = document.querySelector('.autocomplete'); M.Autocomplete.init(inputField, { data: myConvertedData, limit: 50, minLength: 1, }); }); }); } autocompleted(); -
Storing Data Temporarily in Django to be accessed across multiple Devices
I am working on an e-learning platform I have a scenario where a student is doing an timed exam and either their computer crashes or power failure, and hence so computer shuts down What would be a good way to store this information, such that when the user logs in again to their computer or a different device, they can continue from where they left, with the already answered questions. Thanks in advance -
instance error while saving Django form input to model
This error showing when tried to save inputs to model Cannot assign "3380786777": "Registration.nid" must be a "Nid" instance. I am using MySQL database in this project. Tried for hours to fix this. Already inserted values in Nid table and the Nid I tried to insert in Registration table does exist in Nid table. Here is my model: class Nid(models.Model): id = models.BigIntegerField(primary_key=True) fname = models.CharField(db_column='FName', max_length=100, blank=True, null=True) # Field name made lowercase. lname = models.CharField(db_column='LName', max_length=100, blank=True, null=True) # Field name made lowercase. dob = models.DateField() fathers_name = models.CharField(db_column='Fathers_Name', max_length=150, blank=True, null=True) # Field name made lowercase. mothers_name = models.CharField(db_column='Mothers_Name', max_length=150, blank=True, null=True) # Field name made lowercase. address = models.ForeignKey(Address, models.DO_NOTHING, db_column='Address_ID', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'nid' class Registration(models.Model): nid = models.OneToOneField(Nid, models.DO_NOTHING, db_column='NID', primary_key=True) # Field name made lowercase. date = models.DateTimeField(db_column='Date') # Field name made lowercase. center = models.ForeignKey(Center, models.DO_NOTHING, db_column='Center_ID', blank=True, null=True) # Field name made lowercase. mobile_no = models.IntegerField(db_column='Mobile_No', blank=True, null=True) # Field name made lowercase. age = models.IntegerField(db_column='Age') # Field name made lowercase. class Meta: managed = False db_table = 'registration' unique_together = (('mobile_no', 'center'),) Form: class PostForm(forms.Form): NID = forms.IntegerField() Date_of_Birth … -
Trouble Creating QuerySet of Django model objects with self-referential ForeignKey
Simply put I have two models A dialogue model: class Dialogue(models.Model): content = models.TextField() created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) And a choice model: class Choice(models.Model): option = models.CharField(max_length = 255) content = models.TextField() dialogue = models.ForeignKey( Dialogue, related_name = "choices", blank = True, null = True, on_delete = models.CASCADE ) subChoices = models.ForeignKey( "self", related_name = "parent", blank = True, null = True, on_delete = models.CASCADE ) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) You may have noticed the recursive ForeignKey "Choice.subChoices". This is where my issue lies. If I attempt to use the add() method via the instance of this model that I want to be added to a Choice's list of further choices, I get a "'Choice' object has no attribute 'add'". If I attempt to the the reverse and add an instance of the Choice model to a Choice's parents attribute it overwrites instead of creating a query set. Examples of both below: choice1 = Choice.objects.get(id = 1) choice2 = Choice.objects.get(id = 2) choice3 = Choice.objects.get(id = 3) choice1.subChoices.add(choice2) >>> AttributeError: 'Choice' object has no attribute 'add' choice2.parent.add(choice1) choice3.parent.add(choice2) print(choice1.subChoices) >>> Choice object(3) A print statement of choice1.subChoices.all() returns … -
celery app.delay() is keep on waiting for the response, not working
I am trying to experiment with celery with Redis broker in my Django application, but I am having a hard time getting it write can anyone point me where I am missing things my init.py from __future__ import absolute_import from .celery import app as celery_app __all__ = ('celery_app', ) my base_settings.py CELERY_BROKER_URL = 'redis://localhost:6379/' CELERY_RESULT_BACKEND = 'redis://localhost:6379/' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_ALWAYS_EAGER = True my celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.enable_utc = False app.conf.update(timezone='Asia/Kolkata', task_always_eager=True) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) In my views.py @app.task(name="test celery") def add(a, b): print(a, b, a + b) @api_view(['GET']) def testcelery(request): a = request.GET.get('a', 0) b = request.GET.get('b', 0) add.delay(a, b) the output of my celery worker >celery -A lylo worker --loglevel=info -c 5 -------------- celery@LAPTOP-VQHQANA1 v5.1.1 (sun-harmonics) --- ***** ----- -- ******* ---- Windows-10-10.0.19041-SP0 2021-09-08 22:00:46 - *** --- * --- - ** ---------- [config] - ** … -
valueerror invalid model reference, how can i reference correctly
I had to change a number of my ManyToMany relations to reference a string instead of importing the model into the file so to avoid a number of circular importing errors. but when trying to run, now I am getting this error. ValueError: Invalid model reference 'dsi.administration.libraries.Library'. String model references must be of the form 'app_label.ModelName'. I don't know what would be the best way to reference this and I'd love to get anyone's input on this. the reference in question models.ManyToManyField("dsi.administration.libraries.Library", verbose_name='library choices') settings.py installed modules SHARED_APPS = ( "storages", "django_tenants", # mandatory 'dsi.events.event', 'dsi.administration.libraries', 'dsi.account' ) the app folder structure ├── dsi │ ├── account │ │ ├──__init__.py │ │ ├── models.py │ ├── events │ │ ├── event | │ │ ├── __init__.py | │ │ ├── models.py │ │ ├──__init__.py │ ├── administration │ │ ├── libraries | │ │ ├── __init__.py | │ │ ├── models.py │ │ ├── general | │ │ ├── __init__.py | │ │ ├── models.py │ │ ├── __init__.py │ ├── __init__.py │ ├── urls.py │ └── settings.py ├── manage.py -
django server error (500) when DEBUG=False
This is base.py file from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent SECRET_KEY = 'h@1lneuTr@lt1P - Holla!!! this is something crazy, $2423$#@$#@E@e#R3\e[' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ # typical django code... MIDDLEWARE = [ # typical django code... ] ROOT_URLCONF = 'neutraltip.urls' TEMPLATES = [ # typical django code... ] WSGI_APPLICATION = 'neutraltip.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ # typical django code... ] STATIC_URL = '/static/' # Static settings STATICFILES_DIRS = [ BASE_DIR / 'static', ] # Media settings MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' This is production.py from .base import * import environ import django_heroku env = environ.Env( DEBUG=(bool, False), ) SECRET_KEY = 'lol' # right now for convenience I've hard-coded these # despite having environ package DEBUG = False ALLOWED_HOSTS = ['*'] MIDDLEWARE.insert(1, 'whitenoise.middleware.WhiteNoiseMiddleware') DATABASES['default']['CONN_MAX_AGE'] = 60 STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' # Activate Django-Heroku. django_heroku.settings(locals()) I've renamed the original settings.py to base.py, and extended it to production.py. And also updated manage.py, wsgi.py and asgi.py. Basically following this approach -> https://simpleisbetterthancomplex.com/tips/2017/07/03/django-tip-20-working-with-multiple-settings-modules.html Everything looks just fine … -
No reverse match when rendering an email template with uid/token variable
I wrote a view for user signup including email verification. However, once the view tries to render the mail template, it breaks due to the below error. I don't even understand the error itself. Insights would be appreciated. According to some googling it may be that the uid is no string? NoReverseMatch at /signup/ Reverse for 'activate' with keyword arguments '{'uidb64': 'MTE', 'token': 'asnwwr-550108ae10aa04da212561866c8d1ae3'}' not found. 1 pattern(s) tried: ['activate/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] Mail template {% autoescape off %} Hi {{ user.username }}, Please click on the link below to confirm your registration: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} View def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your Poller Account' message = render_to_string('userprofile/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), # Issue might sit here? 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent')