Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django count extremely slow with full text search
I'm using Django SearchRank example to query a PostgreSQL database. The problem is that the final cursor results in very slow methods such as a simple count(). I need it to do pagination (I'm using Django El Pagination) I know that a similar issue was already asked here. However, I don't have here any ManyToMany relation. It's a simple text search copied from the documentation. articles = Article.objects.filter( jonal__slug__in = jornal_slug, publish_date__gte = from_date, publish_date__lte = to_date ) vector = SearchVector('body', weight='A') + SearchVector('title', weight='A') query = SearchQuery(termo) articles = articles.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.3).order_by('rank') -
Confusion about Imagefield
I am learning Django as a beginner. Commonly speaking(documentation-wise), is Imagefield for photos? What field is then for the image files? (dmg for example). Thank you. -
.delete() not working on a record called from signals.py Django
I am creating a Billing Panel. In the part where a duplicate Billing Address assigned to Order instance, it gets automatically deleted and the previous Billing Address gets assigned to the Order. While the previous Billing Instance gets Assigned to the Order but the duplicate Billing Address Instance is not getting deleted. I am a noob. There is not overridden delete method in the models. models.py :- class BillingAddress(models.Model): #Contains address and email and other info class Order(models.Model): billingAddress = billingAddress = models.ForeignKey(BillingAddress, null=True,on_delete=models.SET_NULL ) signals.py :- @receiver(post_save, sender=Order) def dont_save_if_all_fields_matching(sender, instance, created, **kwargs): if created: currentOrder = instance previousBilling = BillingAddress.objects.filter(user=currentOrder.user, firstname=currentOrder.billingAddress.firstname, lastname=currentOrder.billingAddress.lastname, phonenumber=currentOrder.billingAddress.phonenumber, address1=currentOrder.billingAddress.address1, address2=currentOrder.billingAddress.address2, city=currentOrder.billingAddress.city, country=currentOrder.billingAddress.country, state=currentOrder.billingAddress.state, pincode=currentOrder.billingAddress.pincode ) if len(previousBilling) > 0: currentBillingId = currentOrder.billingAddress.id currentOrder.billingAddress = previousBilling[0] currentOrder.save() BillingAddress.objects.get(id=currentBillingId).delete() #The above code is not working -
Using pythonOCC's render function in Django
I have a Django application and I'm using pythonOCC package in it. I have to display the 3D .stl, .stp, .igs files in my template. I have tried to use render() function which in threejs_renderer.py file in the package. Here is my view: from OCC.Extend.DataExchange import read_step_file from OCC.Display.WebGl import x3dom_renderer from OCC.Core.BRep import BRep_Builder from OCC.Core.TopoDS import TopoDS_Shape from OCC.Core.BRepTools import breptools_Read def index(request): shape = read_step_file('test.stp') my_renderer = x3dom_renderer.X3DomRenderer() my_renderer.DisplayShape(shape) my_renderer.render() return render(request, 'index.html') When I call the render() function, the following outputs appear on my vscode console and since flask app created by pythonocc instead of django starts running in localhost, my index.html is never rendered. The output when I call the render function: ** Model Complete Check List ** Check:1 -- Entity (n0:id) 5:#14 Type:CURVE_STYLE Parameter n0.2 (curve_font) not an Entity Check:2 -- Entity (n0:id) 6:#15 Type:CURVE_STYLE Parameter n0.2 (curve_font) not an Entity Check:3 -- Entity (n0:id) 7:#16 Type:CURVE_STYLE Parameter n0.2 (curve_font) not an Entity Check:4 -- Entity (n0:id) 8:#17 Type:CURVE_STYLE Parameter n0.2 (curve_font) not an Entity Check:5 -- Entity (n0:id) 9:#18 Type:CURVE_STYLE Parameter n0.2 (curve_font) not an Entity Check:6 -- Entity (n0:id) 10:#19 Type:CURVE_STYLE Parameter n0.2 (curve_font) not an Entity ## x3dom webgl renderer - … -
pg_dump: fails for contents of table
So I tried to run this command heroku pg:pull postgresql-objective-94323 dbname --app appname This is the error that is thrown back pg_dump: dumping contents of table "public.table_name" events.js:287 throw er; // Unhandled 'error' event ^ Error: write EPIPE at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:92:16) Emitted 'error' event on Socket instance at: at errorOrDestroy (internal/streams/destroy.js:108:12) at Socket.onerror (_stream_readable.js:729:7) at Socket.emit (events.js:310:20) at errorOrDestroy (internal/streams/destroy.js:108:12) at onwriteError (_stream_writable.js:463:5) at onwrite (_stream_writable.js:484:5) at internal/streams/destroy.js:50:7 at Socket._destroy (net.js:677:5) at Socket.destroy (internal/streams/destroy.js:38:8) at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:93:12) { errno: 'EPIPE', code: 'EPIPE', syscall: 'write' } -
Django adding CSS classes to field
I am trying to add an error class to fields of a each form in a formset if a custom clean method detects errors. This does look to do the trick, I load the page, and the field does have the error class in it. but when in the template I add a custom filter to add a form-control class, everything falls apart. # in my inlineformset: def clean(self, *args, **kwargs): if any(self.errors): errors = self.errors return ## 1) Total amount total_amount = 0 for form in self.forms: if self.can_delete and self._should_delete_form(form): continue amount = form.cleaned_data.get('amount') total_amount += amount if total_amount> 100: for form in self.forms: form.fields['amount'].widget.attrs.update({'class': 'error special'}) raise ValidationError(_('Total amount cannot exceed 100%')) And, here is my code for the custom filter: @register.filter(name = 'add_class') def add_class(the_field, class_name): ''' Adds class_name to the string of space-separated CSS classes for this field''' initial_class_names = the_field.css_classes() ## This returns empty string, but it should return 'error special' class_names = initial_class_names + ' ' + class_name if initial_class_names else class_name return the_field.as_widget(attrs = {'class': class_names,}) And, in my template: {# {{ the_field|add_class:"form-control"}} #} #<- This adds the form-control, but removes the other classes added in the clean method {{ the_field }} … -
Django: How can I set form instance as a variable which was defined inside the HTML page?
So my blog has posts and comments. I want the users to be able to edit the comment through a BOOTSTRAP MODAL that opens inside the same page when you click the edit button. But I'm actually facing a problem, now there is a for loop inside the html page where I defined the comment variable : {%for comment in comments%} <button type="button" class="btn btn-warning btn-sm" data-toggle="modal" data- target="#Edit{{comment.id}}Modal">edit test</button> {%endfor%} Code at Views.py : post = Post.objects.get(slug=slug) comments = post.comment_set.all() if request.method == 'POST': editcommentform = CommentForm(request.POST, instance=comment) if editcommentform.is_valid(): editcommentform.save() else: editcommentform = CommentForm(instance=comment) now in my views.py I cannot actually set the instance to comment because I get an error of "comment is not defined" My question is how can i set the instance to comment while it's only defined inside the for loop in the HTML page? Sorry if it may sound unclear or weird, I am new to the field. -
Sending websockets message from inside of Consumer's connect() closes the connection
While tracking down the root cause for this question I stumpled upon an issue with using self.send() from inside the connect() of a AsyncWebsocketConsumer. It closes the websocket instead of sending the message: import json from uuid import UUID from channels.generic.websocket import AsyncWebsocketConsumer from myapp.models import AnalysisResult class AnalysisConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.analysis_id = self.scope['url_route']['kwargs']['analysis_id'] self.analysis_group_name = "analysis_{}".format(self.analysis_id) async def connect(self): await self.channel_layer.group_add(self.analysis_group_name, self.channel_name) # Setting up this whole channel / websocket connection takes a while. Thus, we need # to send an initial update to the client to make sure a (too) fast analysis result # doesn't get lost while we've been busy here. # Problem: This is DISCONNECTING instead of sending the message. await self.send(text_data=json.dumps({ 'progress_percent': 100, 'status_text': "Done already." })) await self.accept() async def disconnect(self, code): await self.channel_layer.group_discard(self.analysis_group_name, self.channel_name) Is that expected behavior and I shouldn't try to send something via the websocket from inside the Consumer's connect() method? Or should that be working? -
update django model instance - save() method not working
I'm trying to update a model field using save(), and the change is not being saved. I have no idea why, can someone help? below is an abbreviated version of the code: models.py class Mandate(models.Model): user_id = models.ForeignKey( User, on_delete=models.SET_NULL, editable=True, null=True, ) id = models.CharField(primary_key=True, max_length=32) mode = models.CharField(max_length=16) ... some other fields def __str__(self): return str(self.id) my_module.py def sync_mandate_locally(customer_id, mandate_id): c = Customer.objects.get(id=customer_id) mandate = client.customer_mandates.with_parent_id(customer_id).get(mandate_id) m, created = Mandate.objects.get_or_create(id=mandate_id, user_id=c.user_id) m.mode = mandate.get('mode') print(f"1. {m.mode = }") m.save() m, created = Mandate.objects.get_or_create(id=mandate_id, user_id=c.user_id) print(f"{created = }") print(f"2. {m.mode = }") output: || 1. m.mode = 'pindakaas' || created = False || 2. m.mode = '' -
Django Modal Create & Update No Jquery
i am trying to implementing the create and update through a pop up modal, i have my code in place however, the code basically will start with create and if the object is created it will take the used to the update and will pull the data in the Modal for updating. the problem is that once the form is submitted in the create view the user is logged out but data is created in the DB and when clicking on the button it should load the data from DB for update but that not happening. the codes are as below: below is my concept code : models.py: class Startup ( models.Model ) : author = models.OneToOneField ( User , on_delete = models.CASCADE ) startup_name = models.CharField ( max_length = 32 , null = False , blank = False ) class Score_Appeal(models.Model): appeal_score = models.ForeignKey(Startup, on_delete = models.CASCADE) appeal_evaluator = models.ForeignKey(User, on_delete = models.CASCADE) appeal = models.CharField ('Appeal', max_length = 100 , null = False , blank = False , choices = Choice.EVALUATION , default = '' ) appeal_comment = models.TextField(max_length = 100, blank = True) views.py: view.py: @login_required @inv_required def global_list(request): startup = Startup.objects.all() return render(request, 'inv_template/global_list.html', {'startup': startup}) … -
Дублирование полей в админке django [closed]
Извиняюсь, если такой вопрос уже был, но сам я не смог найти точного ответа либо понять его, так как недавно изучаю django. Можно ли реализовать в стандартной админке django такой же функционал как в премиум версии плагина ACF на wordpress? То есть, плагин ACF позволяет создавать клоны полей при добавлении записи в админке. Например, мы создаем одно поле изображения или размера товара, а при добавлении записи можем нажать на плюсик рядом с полем и появится его клон и так далее. А потом на странице перебором перебрать все значения этого поля, сколько бы их не получилось. -
Django can I use one Model for multiple Database tables?
I have a problem, I have a database with the following tables: Images(recipeID,image_url) Recipe(recipeID,recipe_title) Preperation(recipeID,preparation) Ingredients(ingredientID,recipeID,amount,unit,unit2,ingredient) I auto-created a models.py file with Django from the database with the following command: python manage.py inspectdb > models.py. In this file, he created all the models and three "strange" models: AllRecipesIngredient, AllRecipesRecipe, and AllRecipesRecipeIngredients. Now I want to know what they are and how I can use the recipes from one model or class like recipes.objects.all(), at the moment it would just give me the title or the preparation. I think the "strange" models he created are a part of what I need but I found no working solution so I hope you can help me. Here is the code: from django.db import models class Images(models.Model): rezept = models.ForeignKey('Rezepte', models.DO_NOTHING, db_column='Rezept_ID', blank=True, null=True) # Field name made lowercase. image_url = models.CharField(db_column='Image_URL', blank=True, null=True,max_length=1000) # Field name made lowercase. class Meta: managed = False db_table = 'Images' class Rezepte(models.Model): rezept_id = models.AutoField(db_column='Rezept_ID', primary_key=True, blank=True) # Field name made lowercase. rezept_title = models.CharField(db_column='Rezept_Title', blank=True, null=True,max_length=1000) # Field name made lowercase. class Meta: managed = False db_table = 'Rezepte' class Zubereitungen(models.Model): zubereitungs = models.OneToOneField(Rezepte, models.DO_NOTHING, db_column='Zubereitungs_ID', primary_key=True, blank=True) # Field name made lowercase. zubereitung = models.TextField(db_column='Zubereitung', … -
Django: Many to Many Relationship puts all object in model in another object
I am trying to have it so I can select which clusters I select for each Issue. However, it auto adds all of them, why is that? -
how can django only render a modal when called
Is it possible to reload a modal without leaving the main page. on the main page i have a table, after clicking on an element i would like to display additional information via modal. The problem is that I have to reload this additional information first, as different information is available for each table element. For example, I could now open a completely new window and cause django to render this window with the tags, but this is ugly. therefore the question would be whether I can deliver the django tags for part of the page (the modal), or can only render the modal later? Since I would like to use the django tags, I don't want to generate an ajax request. is there any trick, how would you do it? Unfortunately, I can't find anything about it, or I'm missing the search terms ... -
Serving private media files from S3 to single page React App (Django DRF backend)
I have set up an S3 bucket on AWS where I upload my sensitive ‘media’ files from my Django DRF + React app. The files are not public. I use boto3 and Django-storages for that and the upload process works fine. I can also download the files for report generation from backend to return PDF response. I would now like to display those files one by one from frontend. It seems like I now have two options: Create a route in Django API/urls to handle media requests and point the app to the media directory. This way, the AWS login is handled by the backend server. This seems to beat the point of using a CDN as all media requests would go via the backend server? Incorporate login credentials to React front end. This seems insecure. What would be the recommended way to achieve this? I can’t seem to find the required information. Thank you. -
Django API REST error using Postman: "detail": "Authentication credentials were not provided."
I learn about Django API REST and have implemented the quickstart project (https://www.django-rest-framework.org/tutorial/quickstart/). It works fine locally but I would like to use API with Postman but it dose'nt works I got 401 Unauthorized error I try adding 'DEFAULT_AUTHENTICATION_CLASSES' key in settings.py but dose'nt works neither settings.py INSTALLED_APPS = [ 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10 } moreover, I have a huge traceback in terminal when saving projects (below), even if py manage.py runserver works Traceback (most recent call last): File "C:\Users\jl3.PRT-063\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\jl3.PRT-063\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 196, in finish_response self.close() File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\core\servers\basehttp.py", line 111, in close super().close() File "C:\Users\jl3.PRT-063\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\simple_server.py", line 38, in close SimpleHandler.close(self) File "C:\Users\jl3.PRT-063\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 334, in close self.result.close() File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\http\response.py", line 252, in close signals.request_finished.send(sender=self._handler_class) File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\dispatch\dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\dispatch\dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\db\__init__.py", line 57, in close_old_connections conn.close_if_unusable_or_obsolete() File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\db\backends\base\base.py", line 514, in close_if_unusable_or_obsolete self.close() File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 248, in close if not self.is_in_memory_db(): File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 367, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type … -
How to properly make a query in Django?
I've ran into a little problem. I want to construct a proper queryset to get values which represent the number of the expenses per category to display this like that. This is what I got now: class CategoryListView(ListView): model = Category paginate_by = 5 def get_context_data(self, *, category_object_list=None, **kwargs): **categories = Category.objects.annotate(Count('expense')) queryset = categories.values('expense__count')** return super().get_context_data( category_object_list=queryset, **kwargs) Of course it doesnt work and I have terrible table like this. I suppose the problem isn't in HTML but in my absolutely wrong query... What should I do? This is my HTML in case it would be needed: {% for category in object_list %} <tr> <td> {{ category.name|default:"-" }} </td> <td> {% for number in category_object_list %} {{ number.expense__count }} {% endfor %} </td> <td> <a href="{% url 'expenses:category-update' category.id %}">edit</a> <a href="{% url 'expenses:category-delete' category.id %}">delete</a> </td> {% endfor %} </tr> Also my models.py: class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('-date', '-pk') category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' -
double inheritence of ModelForm class, can't change required fields
I have a ModelForm class that I use as a parent for all my other form classes. It looks like this: class BootstrapForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(BootstrapForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control text-center' if field != 'email': self.fields[field].widget.attrs['class'] += ' text-capitalize' for error in self.errors: if error in self.fields: self.fields[error].widget.attrs['class'] += ' is-invalid' Also I have a model that has a field 'tax_no' with blank set to True: class Institution(CustomModel): name = models.CharField(max_length=256, null=False, blank=False, verbose_name=_('nazwa')) address = models.ForeignKey('Address', on_delete=models.PROTECT, null=False, blank=False, verbose_name=_('adres')) phone = PhoneNumberField(null=True, blank=True, verbose_name=_('telefon')) tax_no = models.CharField(max_length=15, null=True, blank=True, validators=[validate_tax_number, ], verbose_name=_('NIP')) What I want is a model that allows empty tax_no field by default but I want a possibility to set it as a required on demand. My problem is that when I try set the field to required like this: class InvoiceInstitutionForm(BootstrapForm): class Meta: model = Institution exclude = ('address',) def __init__(self,*args, **kwargs): super(InvoiceInstitutionForm, self).__init__(*args,**kwargs) print(self.fields['tax_no'].required) self.fields['tax_no'].required = True it only works correctly if the InvoiceInstitutionForm inherits directly from forms.ModelForm. It doesn't work when inherited from BootsrapForm class. Any ideas why it doesn't work and how to fix it? -
ModuleNotFoundError: No module named 'crispy_forms'
django-crispy-forms is present in requirements.txt (added using pip freeze > requirements.txt) requirements.txt asgiref==3.2.10 autopep8==1.5.4 beautifulsoup4==4.9.1 certifi==2020.6.20 chardet==3.0.4 Django==3.1 django-crispy-forms==1.9.2 feedparser==5.2.1 idna==2.10 Pillow==7.2.0 pycodestyle==2.6.0 python-dateutil==2.8.1 pytz==2020.1 requests==2.24.0 six==1.15.0 soupsieve==2.0.1 sqlparse==0.3.1 toml==0.10.1 urllib3==1.25.10 heroku run pip freeze appdirs==1.4.4 asgiref==3.2.10 certifi==2020.6.20 distlib==0.3.1 Django==3.1.1 filelock==3.0.12 gunicorn==20.0.4 pipenv==2018.5.18 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 virtualenv==20.0.31 virtualenv-clone==0.5.4 whitenoise==5.2.0 So, this leads to Application Error on heroku deploy and the heroku logs --tail gives ModuleNotFoundError: No module named 'crispy_forms' -
Send changes in my django application to the client via socket.io using django signal
Recently I received a demand on the company I work for. They wanted me to build a API using django that will give support a chatbot client. Basically It is supposed to work like that: The API receives a JSON object, containing a message_receiver and a message_body, and it is send to the chatbot client that will handle all the "message-sending" stuff. Great! After doing some research I decided to, instead of going for a logic in which the client periodically pings the server in search for new messages to be sent, go for the inverse logic, in which whenever the server receives a message It would automatically emit an event for the client telling him to send the message. For doing that, I stumbled in some interesting tools, like socket.io, and django channels. I particularly liked socket.io more. So before getting my hands dirty, I drew all the process and ran into a problem that I couldn't find a straight answer to on the internet, most of the tutorials I looked into focused on showing how the communication client-server works, but I couldn't find one that would clearly tell me how to make the communication between django app - … -
Can I figure out why my apache server is only accessible via a proxy?
I just deployed a django app on a linux based server with wsgi_module. The app works perfectly when I use a VPN, but without that, I get "This site can't be reached." Here is the few lines I added in httpd.conf <Directory /path/to/myapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess ip_adress python-home=/usr/local/apache/htdocs/env python- path=/path/to/myapp/ WSGIProcessGroup ip_adress WSGIScriptAlias ip_adress /path/to/myapp/wsgi.py process- group=ip_adress Don't know where is the problem. -
Django oscar custom benefits
I am building a commercial app using Django and Django-oscar and I am trying to create a custom benefit. I have read Oscar's documentation here and I have also found this relative question in Stack Overflow. I have forked Oscar's offer app and created a benefits.py file where I want to put my custom benefit. I also have change the INSTALLED_APPS setting to include my offer app and not Oscar's default. The problem is that Oscar's doesn't see the benefits.py file no matter what I try. At first I thought that something is wrong with my custom Benefit Class but I tried using Oscar's example and that didn't work either. Then I wrote a piece of code designed to fail (for example a variable which had never been assigned a value to) but it didn't so I am thinking that the file is never accessed. Does anybody knows what might be wrong? I am using Django 2.2 and Oscar 2.0.4 Thanks in advance for your time! -
Django Test message passed in with Http404
I'm trying to check if my app passes a message alongside my Http404 call. However I've not been able to access that message inside the tests, only via hacking manually in shell. my_app.views.py: from django.http import Http404 def index(request): raise Http404("My message") Then in this app's test file I call: from django.test import TestCase from django.urls import reverse class AppIndexView(TestCase): def test_index_view(self): response = self.client.get(reverse("my_app:index")) self.assertEqual(response.status_code, 404) # This checks self.assertEqual(response.context["reason"], "My message" # This gives: KeyError: 'reason' # However if I manually trace these steps I can access this key. self.assertContains(response, "My Message") # This gives: AssertionError: 404 != 200 : Couldn't # retrieve content: Response code was 404 (expected 200) # Even though the status code test checks. I also have tried various version to get that message with response.exception, response.context.exception etc. as detailed in this question If I execute in django's shell I can access that message: >>> from django.test import Client >>> from django.urls import reverse >>> from django.test.utils import setup_test_environment >>> setup_test_environment() >>> client=Client() >>> response = client.get(reverse("my_app:index")) >>> response.context["reason"] 'My Message' How can I get access to this message in my tests.py? -
Django / Anaconda - Can not start server
I made a new django project on a different machine (PC) in a conda enviroment. Now I copied the django project folder and created a new enviroment on the new PC with conda. I installed everything like on the "old" machine but however if I type python manage.py runserver it throws a message: Image Does someone know if something is missing or what can I do to run the django project on the new pc? I have latest conda version 4.8.4, django version 3.0.3 -
How to Check m2m field if exist? if yes add if no remove
How to check m2m field if user is exist -remove. if not add? here is my coed , where im wrong? because it's always just remove if user.following.exists(): user.following.remove(following_profile) return Response({'message': 'now you are unfollow user'}, status=status.HTTP_200_OK) else: user.following.add(following_profile) return Response({'message': 'You are following user'}, status=status.HTTP_200_OK)