Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Performance | Recalculating a field value in all related models after updating a model in Django
I want to learn what is the best approach to recalculate a model field value(total_cost in my Product model class) in all related models after updating a model. I wrote a piece of code and it works but it takes long time. How can I speed up my code? Here is model classes #models.py class Product(..): total_cost = models.FloatField(...) materials = models.ManyToManyField(Material, through="MaterialProduct") def calculate_cost(self): return round(calc_material_price(self.materialproduct_set.all()),2) def calc_material_price(self, mylist): res = 0 for m in mylist: res += m.material.price * m.material_rate return res class Material(..): price = models.FloatField(...) class MaterialProduct(..): product = models.ForeignKey(Product, ..) material = models.ForeignKey(Material, ..) material_rate = models.FloatField() And my serializer sample class UpdateProductMaterialSerializer(..): #... def update(self, instance, validated_data): #in front-end total cost calculated and I assign it here directly instance.total_cost = self.initial_data.get("total_cost") instance.save() mylist_data = self.initial_data.get("mylist") material_list_for_update = [] for item in mylist_data: material = item.get("material") material_instance = Material.objects.get(pk=material["id"]) # I use this list for updating all Products material_list_for_update.append(material_instance) material_rate = item.get("material_rate") mp = MaterialProduct.objects.filter(product=instance, material=material_instance).first() mp.material_rate = material_rate mp.save()# here my one product is updated successfully # TO UPDATE ALL PRODUCTS I call below method # But this takes 15 seconds update_all_product_by_sent_materials(material_list_for_update) return instance def update_all_product_by_sent_materials(self, material_list): for material in material_list: for mp in … -
How could I send email from users who are logged in to admin?
I am working on a project to send the withdraw request from user who is logged in to admin. In this case I don't have to send mail to users instead I will have to send mail to admin official email address for notification. I used reply_to, but it showed me that it is unexpected argument views.py @login_required def withdraw(request): form_class = WithdrawBalance if request.method == 'POST': form = form_class(request.POST) obj = form.save(commit=False) obj.owner = request.user obj.save() messages.success(request, f'Your request has been submitted.') send_mail('New Withdrawal Request', 'Hello there, A new withdrawal request has been received.', request.user.email, ['bilalkhangood4@gmail.com'], fail_silently=False) return redirect('index') else: form = form_class() context = {'form': form} return render(request, 'nextone/withdraw.html', context) settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'bilalkhangood4@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 ACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_SSL = False -
How can I update associated models in a django DeleteView
I have a couple of models, Content and Hostname. Hostname has a content_id associating the models: class Content(models.Model): name = models.CharField(max_length=120) message = models.TextField() class Hostname(models.Model): """ Hostname model """ name = models.CharField(max_length=250) content = models.ForeignKey(Content, on_delete=models.DO_NOTHING, null=True) On the content delete form/view, I have a drop-down selector to specify what content should be assigned to hostnames that are associated with the content being deleted. Contents: Content1 Content2 Content3 Hostnames Hostname1 (content_id: Content1) Hostname2 (content_id: Content2) Action: Delete Content2, user selects Content3 in the drop-down when deleting Content2 Hostname2 should be updated to be associated with Content3 The template for the content_confirm_delete looks like this, when selecting the content_id: <select name="content_id"> {% for new_content in contents %} {% if new_content.id != content.id %} <option value="{{ new_content.id }}" {% if default_content == new_content.name %}selected{% endif %}>{{ new_content.name }}</option> {% endif %} {% endfor %} </select> The content delete is using a generic.DeleteView: class ContentsDeleteView(generic.DeleteView): model = Content success_url = reverse_lazy('content.list') -
Running of os system before actual file content is formed
I'm currently encountering one major problem: script executing the command before file being formed. I'm currently running the codes on the Unix server using Django framework. Please refer to the code below (these are the portions of my main code): views.py get_bags = request.POST.getlist('bags[]') get_bags_others = request.POST.get('bagsss') f2 = open(os.path.join(Path, "bags.txt"), "w+") if get_bags == None: f2.write('') else: string_bags = ''.join(get_bags) f2.write(string_bags) if get_bags_others != '': f2a = open(os.path.join(Path, "bags.txt"), "a+") f2a.write(get_bags_others) ... os.system("/home/USER/anaconda3/bin/python /home/USER/AutoML/ML_AutoML_GUI.py") html <form id='upload' method="post" enctype="multipart/form-data" onsubmit="uploadFile();"> {% csrf_token %} <h4 style="font-size: 0.95em"><u>BAGs</u></h4> <input id="21" type="checkbox" name="bags[]" value="10 " /> <label for="21">10</label> <br /> <input id="22" type="checkbox" name="bags[]" value="20 " /> <label for="22">20</label> <br /> <input id="23" type="checkbox" name="bags[]" value="30 " /> <label for="23">30</label> <br /> <input id="24" type="checkbox" name="bags[]" value="40 " /> <label for="24">40</label> <br /> </form> In the code above, the file that I've tried to form here is 'bags.txt'. However, it kept giving me the value of NULL, which shows that the command is executed before the file is formed (through checking the checkbox). Also, the code ... above did not change anything with regards to the content of 'bags.txt'. The code of time.sleep(30) before os.system("/home/USER/anaconda3/bin/python /home/USER/AutoML/ML_AutoML_GUI.py") but it does not show any … -
How to place a custom drop down in django model admin page? [duplicate]
This question already has an answer here: django admin - add custom form fields that are not part of the model 5 answers I was unable create a custom drop down in Django model admin page. I need to create a custom drop down which have some custom options. After selecting the option and saving the data i need to get that option in the save_model() method -
How to alter or customize django admin page. (removing some built-in help texts) [duplicate]
This question already has an answer here: How to override and extend basic Django admin templates? 11 answers I'm customizing my django admin page. And on my add user form in admin page there is this help text that i want to remove that says, "First, enter a username and password. Then, you'll be able to edit more user options." And I inherited BaseUserAdmin in my UserAdmin class at my admins.py. I don't know if it has something to do with it. I'm new to django. Any help would be really appreaciated. Thank you. -
After saving form1, sending some information to form2
i have 2 form page page1 and page2 page1 fields are: name,game,info,extra,t1 (foreignkey field), t2 (foreignkey field) page 2 fields are: name,extra,t1 (foreignkey field), t2 (foreignkey field) After saved the of page1, I use redirect to page2 if form.is_valid(): f= form.save(commit=False) ... f.save() return redirect(reverse('page2', kwargs={"k":v ,"k1":v1})) How do I send some information as a value to the form on page 2 after saving the data on page 1? -
Mysql gone away with peewee as second database in Django
I'm using peewee to access a remote MySql database to retrieve data that I need to display in a Django app. It means that peewee isn't really used to access the main db but just to like, define custom models: Example in databases.py : from django.conf import settings from playhouse.pool import PooledMySQLDatabase database = PooledMySQLDatabase( settings.DB_PEEWEE, **{ "use_unicode": True, "charset": "utf8", "max_connections": 32, "stale_timeout": 300, # 5 minutes. "password": settings.DB_PEEWEE_PSWRD, "user": settings.DB_PEEWEE_USER, "host": settings.DB_PEEWEE_HOST, "port": settings.DB_PEEWEE_PORT, } ) in models.py: from .databases import database class BaseModel(peewee.Model): class Meta: database = database class CountryGroups(BaseModel): africa = peewee.CharField(null=True) group_code = peewee.AutoField() group_name = peewee.CharField() latin_eur = peewee.CharField(null=True) type = peewee.CharField() class Meta: table_name = "country_groups" ... # other main django models So the model can be easily called from the views.py file as : CountryGroups_list = ( CountryGroups.select() .where(CountryGroups.group_name << ["ERROR", "INFO"]) .order_by(CountryGroups.group_name.desc()) .limit(1000) ) I can run the query fine. But I get an error after 24 hours where the connection is broken: (2006, "MySQL server has gone away (error(32, 'Broken pipe'))") The suggested method of solving this in Django is trough the usage of a middleware but this assume that in that case peewee related db is the main one, … -
Capturing values from url in post request in Django
I want to capture url values from a url into my views in a post request. My urls.py looks like below from django.urls import path from . import views as projects_views urlpatterns = [ path('<str:project_id>/comments', projects_views.ProjectCommentList.as_view(), name="project_comments"), ] and I want to capture the value project_id in my ListCreateAPIView. Get call works fine. My views.py looks like below class ProjectCommentList(generics.ListCreateAPIView): queryset = projects_models.Comment.objects.all() serializer_class = projects_serializers.CommentSerializer def get(self, request, project_id=None): queryset = self.filter_queryset(self.get_queryset()) queryset = queryset.filter(project__id=project_id) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) def perform_create(self, serializer): project_id = ### Need "project_id" here project = projects_models.Project.objects.get(id=data.get('project_id')) serializer.save(project=project) How can this be done? -
How to fix " 'Query' object has no attribute 'contains_column_references'"
As i'm tring to insert some data using POST request into mysql dataBase i'm getting an error informing me that AttributeError: 'Query' object has no attribute 'contains_column_references' Internal Server Error: /add_borrow/ Traceback (most recent call last): File "D:\pyvenv\pyvenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\pyvenv\pyvenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\pyvenv\pyvenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python_workspace\dms\app01\views.py", line 23, in inner return func(req, *args, **kwargs) File "D:\Python_workspace\dms\app01\views.py", line 286, in add_borrow end_time=end_time, number=number, contents=content ,device_id=device) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\query.py", line 422, in create obj.save(force_insert=True, using=self.db) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\base.py", line 779, in save_base force_update, using, update_fields, File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\base.py", line 908, in _do_insert using=using, raw=raw) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1334, in execute_sql for sql, params in self.as_sql(): File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1278, in as_sql for obj in self.query.objs File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1278, in <listcomp> for obj in self.query.objs File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1277, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) … -
Solution for MS SQL databse
We are in django 2.1 and thinkg about upgrade to django 2.2. But we currently using django-azure-pyodbc to connect to the MS SQL database, I see django-azure-pyodbc only support django 2.1. Is there a replacement plugin for django 2.2 or any other solutions? -
Django custom reverse manager using a through model
I have a set of models where a Student is assigned multiple Classes via another model, ClassStudentMapping, which has a field where I can set which classes a student has on a particular day. models.py class Student (models.Model): ... class Class(models.Model): ... students = models.ManyToManyField(Student, related_name='classes', through="ClassStudentMapping") class QuestionMemberMapping(models.Model): class = models.ForeignKey(Class) student = models.ForeignKey(Student) DAYS_OF_THE_WEEK = [ ('0', 'Monday'), ('1', 'Tuesday'), ('2', 'Wednesday'), ('3', 'Thursday'), ('4', 'Friday'), ('5', 'Saturday'), ('6', 'Sunday'), ] days = ArrayField(models.CharField(max_length=1, choices=DAYS_OF_THE_WEEK), size=20, default=list(range(0,7))) So if this_student is an instance of Student, then I can obviously get all the classes a student has via student.classes.all(). I want to be able to use a custom manager to call a custom query to get all the classes a student has on the current day. class ClassTodayManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(classstudentmapping__days__contains=[str(datetime.today().weekday())]) But I can't figure out where to put this manager so that I can invoke it via something like student.today_classes.all(). Following the Django docs rather naively, I tried: class Class(models.Model): today_classes = ClassTodayManager() But that resulted in, "AttributeError: 'Student' object has no attribute 'today_classes'. I realized I needed a custom reverse manager, and tried student.classes(manager='today_classes'). But weirdly that is returning multiples of every result -- two for … -
How to access Roles and permissions to generic views
I am very new to Django. Right now I am working on Roles and Permission with Django rest framwork. I have discovered https://django-role-permissions.readthedocs.io/en/stable/setup.html By using this I can check roles and permission. But when going in generic views like generics.RetrieveUpdateDestroyAPIView I don't want to override the three methods. Is any way can I implement with DRY principle or any best practice. Is any way URL restrictions based on user roles and permission or any before action for views? -
How can I query using two keys in django-model
I have following tables in the models ACCOUNT_MSTR with ACCOUNT_ID as Primary Key EXPERIMENT_MSTR with ID AS Primary Key, a Foreign Key ACCOUNT_ID Reference to ACCOUNT_MSTR, and another Foreign Key TEST_ID refer to TEST_MSTR class Experiments_Mstr(models.Model): ID = models.AutoField(primary_key=True) EXPERIMENT_ID = models.IntegerField() ACCOUNT_ID = models.ForeignKey(to='login.Account_Mstr', to_field='ACCOUNT_ID', on_delete=models.CASCADE) USER_ID = models.ForeignKey(to='login.User_Mstr', to_field='USER_ID', on_delete=models.CASCADE) TEST_ID = models.ForeignKey(to='ml.Test_Mstr', to_field='ID', on_delete=models.CASCADE) STATUS = models.CharField(max_length=10, default='ACTIVE', blank=False) TOTAL_TIME = models.IntegerField(default=700, blank=False) FIRST_DROP = models.IntegerField(default=310, blank=False) SECOND_DROP = models.IntegerField(default=510, blank=False) DATAFILE_PATH = models.CharField(max_length=256, default='/tmp', blank=False) CREATED_AT = models.DateTimeField(auto_now=True, blank=False) CREATED_BY = models.CharField(max_length=10, default='SYSTEM', blank=False) MODIFIED_AT = models.DateTimeField(auto_now=True, blank=False) MODIFIED_BY = models.CharField(max_length=10, default='SYSTEM', blank=False) TEST MSTR with ID as Primary Key, a Foreign Key ACCOUNT_ID Reference to ACCOUNT_MSTR class Test_Mstr(models.Model): ID = models.AutoField(primary_key=True) ACCOUNT_ID = models.ForeignKey(to='login.Account_Mstr', to_field='ACCOUNT_ID', on_delete=models.CASCADE) TEST_NAME = models.CharField(max_length=256, null=False, blank=False) TEST_SHORT_NAME = models.CharField(max_length=10, null=False, blank=False) TEST_DESCRIPTION = models.TextField() CREATED_AT = models.DateTimeField(auto_now=True, blank=False) CREATED_BY = models.CharField(max_length=10, default='SYSTEM', blank=False) MODIFIED_AT = models.DateTimeField(auto_now=True, blank=False) MODIFIED_BY = models.CharField(max_length=10, default='SYSTEM', blank=False) and also a Table: class ExperimentsTable(tables.Table): EXPERIMENT_ID = tables.LinkColumn('experimentDetails', args=[tables.A('EXPERIMENT_ID')]) TEST_ID = tables.Column(accessor='TEST_ID.TEST_SHORT_NAME') SELECTION = tables.CheckBoxColumn(verbose_name=('SELECTION'), accessor='ID', attrs={ "th__input": {"onclick": "toggle(this)"}}) class Meta: model = models.Experiments_Mstr exclude = ('ID', 'ACCOUNT_ID', 'USER_ID', 'DATAFILE_PATH', 'TOTAL_TIME', 'FIRST_DROP', 'SECOND_DROP', 'STATUS', 'MODIFIED_AT', 'MODIFIED_BY',) attrs = {'class': 'table'} What I am doing now is … -
When I fetch all the data in Object in Django, get the error like ''str' object has no attribute 'values'"
I want to get the all the values inside the object, obj.values() method and I got the error like ''str' object has no attribute 'values'" **Views.py** def upload_list(request): pdf = Client_files.objects.all() if request.method == 'POST': obj = request.POST.get('btSelectItem') print(obj.values()) return render(request, 'uploadpdf.html', {'pdf' : pdf,}) -
No value for argument 'on_delete'
I am trying to run some python code, using django, but it is returning that "No value for argument 'on_delete' in constructor call". from django.db import models from django.contrib.auth.models import User class Game(models.Model): first_player = models.ForeignKey(User, related_name="games_first_player") second_player = models.ForeignKey(User, related_name="games_second_player") start_time = models.DateTimeField(auto_now_add=True) last_active = models.DateTimeField(auto_now=True) class Move(models.Model): x = models.IntegerField() y = models.IntegerField() comment = models.CharField(max_length=300, blank=True) by_first_player = models.BooleanField() game = models.ForeignKey(Game, on_delete=models.CASCADE) -
How to fix "no such table: PurchaseHistory_purchasehistory" on Django / Why is there nothing to migrate?
I receive the error no such table: PurchaseHistory_purchasehistory I have tried makemigrations and migrate and cleared pycache and deleted migrations to no avail. Is there some way I could possibly nuke all past migrations and run makemigrations from scratch again? models.py class PurchaseHistory(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="purchase_history") is_one_invested = models.BooleanField(default=False) def __str__(self): return self.user.username class Meta: app_label = 'PurchaseHistory' payments/views.py def charge(request): if request.method == 'POST': charge = stripe.Charge.create( amount=500, currency='usd', description='A Django charge', source=request.POST['stripeToken'] ) if request.user.is_authenticated: if PurchaseHistory.objects.filter(user=request.user).exists(): request.user.purchase_history.is_one_invested = True request.user.purchase_history.save() return render(request, 'charge.html') It should be making a change to my database but it appears to me that my migrations are not adding my model correctly. I know I'm doing something wrong and I'd like someone to show me how to fix this. I viewed many similar questions and tried many answers and nothing is working. -
Psycopg2 invalid json when returning postgres query
I am using Django to access a stored function in my postgres DB. When I execute the function inside of Postgres, it returns doublequotes and valid json. However, when I call the function from Django (which uses psycopg2) the doublequotes are removed and single quotes replace them. It seems psycopg2 is doing some type of conversion to lists / dictionary in the background. However, I need to keep the json. Any ideas how to resolve this? -
Django-filter field name is a python builtin keyword
I'm trying to rebuild a legacy API with DRF and django-filter. One of the field names is from, but from = DateTimeFilter(field_name="created_dt", lookup_expr="gte") is not valid Python. Can I name the variable from_ = DateTimeFilter(...) but still expose the API parameter as ?from= to users? -
How to import and edit variable from model associated with currently logged in user
I want to import a variable from a model associated with the currently logged in user. My model uses a one to one relationship with the built in User model. After importing the variable I want to change it to True for whatever user is currently logged in. I've tried messing with my import statement and got it to work correctly It's giving me "PurchaseHistory() got an unexpected keyword argument 'id'" when trying to edit the variable. I know this is my misunderstanding of a code snippet I found online, and I would just like someone to help me fix it. #models.py class PurchaseHistory(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) InvestingOne = models.BooleanField(default=False) def __str__(self): return self.user.username class Meta: abstract = True app_label = 'PurchaseHistory' #payments/views.py def charge(request): if request.method == 'POST': charge = stripe.Charge.create( amount=500, currency='usd', description='A Django charge', source=request.POST['stripeToken'] ) post = PurchaseHistory(id=InvestingOne) post.InvestingOne = True post.save() return render(request, 'charge.html') I believe I provided good information to help me fix this. Let me know if there's any additional details I should provide. Thank you. -
Django ORM individual query raw SQLs are different when they are bound with OR
I apologize for formatting eyesores in advance. Feel free to edit my question for better readability. I have four models: class Datasets(models.Model): name = models.CharField(max_length=150) description = models.TextField() class Assay(models.Model): dataset = models.ForeignKey(Datasets) name = models.CharField(max_length=150) class = models.CharField(max_length=150) class Compounds(models.Model): dataset = models.ForeignKey(Datasets) name = models.TextField() deleted = models.BooleanField(default=False) class Assays(models.Model): compound = models.ForeignKey(Compounds) assay = models.ForeignKey(Assay) value = models.DecimalField(max_digits=30, decimal_places=16) deleted = models.BooleanField(default=False) I am building queries with user input depending on the Assay picked. I am using JOINs to filter results based on reverse relations. User picks the Assay and I filter the returned compounds based on the selection. Users can also pick 'No Assay' option, which should return the compounds with no registered assays (i.e. no entries in Assays model for that compound). selected_assay_id = 5 # Received from frontend no_assay_option_selected = True/False # Received from frontend dataset_id = 1 filter_query = Q() filter_query.add(Q(**{ 'assays__assay__id': selected_assay_id, 'assays__compound__id': F('id'), 'assays__deleted': False }), Q.OR) if no_assay_option_selected: filter_query.add(~Q(**{ 'assays__deleted': False, 'assays__compound__id': F('id') }), Q.OR) compounds = Compounds.objects.filter(filter_query, dataset__id=dataset_id).distinct() When I pick an assay, it works great. When I pick 'No Assay', it works great. But when I pick an assay and also 'No Assay', all the compounds are returned … -
Django - Bokeh Graph
First time I use bokeh and the graph does not show up. Just a blank html page views.py def home(request): plot = figure() # x coord y coord plot.circle([1,10,35,27],[0,0,0,0],size=20,color="blue") script,div = components(plot) return render(request,"bokeh/home.html",{'script':script,'div':div}) home.html <div class="container text-center"> <h1>HELLO</h1> {{div| safe}} </div> Am I missing something? Thanks -
How can I integrate PayPal with my django application, using Django Rest Framework?
I'm trying to use PayPal with Django Rest Framework, but I don't know how to start with this, any idea how to do it? -
Changing a button depending on whether a user has liked a post or not
I am creating a social media website where users can like each others posts. So far, I have implemented most of this, however I am missing one vital part. This is changing the text within a button, depending on if a user has liked a post or not. The 'tuser' variable finds a user within the many to many field named 'likes' which is on the Post class. Depending on whether it exists or not. I pass a variable through to my 'home' template, which then if it exists, display certain text in a button. models.py: class Post(models.Model): file = models.ImageField(upload_to='images/') summary = models.TextField(max_length=600) pub_date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, through='Like', related_name='likes') def __str__(self): return self.user.username def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') def summary_pretty(self): return self.summary[:50] @property def total_likes(self): return self.likes.count() class Like(models.Model): status = models.BooleanField() post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) views.py def likepost(request, post_id): if request.method == 'POST': post = get_object_or_404(Post, pk=post_id) user = request.user if post.likes.filter(id=user.id).exists(): tuser = post.likes.filter(id=user.id) post.likes.remove(user) if tuser: return redirect('home', {'tuser': tuser}) else: return redirect('home') else: like = Like() like.post = post like.user = user like.status = False like.save() post.likes.add(user) return redirect('home') template code: {% if tuser … -
Django's urls file interpretes twice
I spotted a really weird behavior in my Django project. My urls.py just gets interpreted twice for some reason, which is unfortunately causing a lot of trouble. For debugging, I put these two lines import traceback tracebak.print_stack() into my urls.py file. This is the output I get when I do ./manage.py runserver: File "/usr/lib/python3.7/threading.py", line 890, in _bootstrap self._bootstrap_inner() File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/user/project/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/user/project/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/user/project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/user/project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/user/project/venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/user/project/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/user/project/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/user/project/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 398, in check for pattern in self.url_patterns: File "/home/user/project/venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/user/project/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/user/project/venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/user/project/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 572, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", …