Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
limiting fetch data in django-celery acting as a consumer from rabbitmq queue acting as a producer
I want to retrieve 10 data message in every period of django-celery periodic task from a rabbitmq queue containing 100000 data messages. everything works well. but I don't know how can I stop fetching data if 10 data messages have been retrieve in the specific period. here is my task.py @periodic_task(run_every=(crontab(minute='*/1')), name="task", ignore_result=True) def task(): connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='name') def callback(ch, method, properties, body): # do sth channel.basic_qos(prefetch_count=10, global_qos=True) channel.basic_consume(queue='name', on_message_callback=callback) channel.start_consuming() and here is my rabbitmq producer connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='name') for i in range(10000000): channel.basic_publish(exchange='', routing_key='name', body=msg) -
No reverse match error. Reverse for 'user-profile' with arguments '('',)' not found
I have created a messaging function on my website where logged in and guest users can send messages to other users. I have created an inbox for the logged in users to store these messages. When opening up a message from a guest (someone who doesn't have an account) I get an error: Reverse for 'user-profile' with arguments '('',)' not found. Based on my digging on the web I think this may be due to the fact that the guest user doesnt have a name attached? Could this be it and how would I fix it? Views.py: def createMessage(request,pk): recipient = Profile.objects.get(id=pk) form = MessageForm() try: sender = request.user.profile except: sender = None if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): message = form.save(commit=False) message.sender = sender message.recipient = recipient if sender: message.name = sender.name message.email = sender.email message.save() messages.success(request, 'Your message was successfully sent!') return redirect('user-profile', pk=recipient.id) context = {'recipient': recipient, 'form': form} return render(request, 'users/message_form.html', context) Models.py: class Message(models.Model): sender = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, blank=True) recipient = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, blank=True, related_name="messages") name = models.CharField(max_length=200, null=True, blank=True) email = models.EmailField(max_length=200, null=True, blank=True) subject = models.CharField(max_length=200, null=True, blank=True) body = models.TextField() is_read = models.BooleanField(default=False, null=True) created = models.DateTimeField(auto_now_add=True) … -
Django How to add a User Foreignkey inside a User model?
I'm trying to insert a foreignkey of the User inside of the user model but I keep getting error. As as user I want to have two purposes, I can do i do a book to get my pets taken care of and also i can take care of other pets class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=255, default='John Doe') pet_sitter = models.ForeignKey('User',on_delete=models.CASCADE)//--->User inside User I tried get_user_model() it showed errors too// pet_appointments= models.ManyToManyField( 'User', through=Booking, through_fields=('patient', 'doctor') ) class Booking(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() owner_of_pet = models.ForeignKey(get_user_model(),related_name = "User",on_delete=models.CASCADE, blank=True,null=True) sitter = models.ForeignKey('User', on_delete=models.CASCADE) enter code here =============== error django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'api.User' that has not been installed -
Django Constraining Foreign Keys for multiple nested objects
Let's start with the models: class Brand(models.Model): id = models.UUIDField(primary_key=True name = models.CharField(max_length=255) class ProductLine(models.Model): id = models.UUIDField(primary_key=True name = models.CharField(max_length=255) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) class Product(models.Model): id = models.UUIDField(primary_key=True name = models.CharField(max_length=255) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) product_line = models.ForeignKey(ProductLine, on_delete=models.CASCADE, blank=True, null=True) So we have brands. Brands can have 0 or more product_lines. A product always has a brand, and may also be within a product_line. My goal is to constrain the product_line of a product to also have the same brand as the product itself. For example: Brand A has 2 product_lines: Premium, Standard Brand B has 1 product_line: Platinum Suppose we have a product that belongs to brand B. I want to allow the product_line to be either null or Platinum, but not one of the product_lines that belong to Brand A (Premium or Standard) I'm not sure how to achieve this, or even if this should happen in serializers, at the model level, or somewhere else. Any help from seasoned django-ers would be much appreciated! -
Consequences of overriding __hash__ of Django models?
I have a quite complex potentially time-demanding system where Django model instances are stored and "indexed" (for the actual purpose of the system and for caching for perfomance during its execution) in sets and dicts. Thousands of CRUD operations are performed on those. Since these hashable instances are stored, this means the Django model __hashable__ method is run thousands of times: class Model(object): ... def __hash__(self): return hash(self._get_pk_val()) As efficient as this is, when called that many times, it does add up in time performance. When I use the model pk as dict keys or in sets the performance improvement is noticeable. Now, I cannot just replace all these instances with pks for practical terms, so I was thinking of overriding the method as follows in all pertinent models: def __hash__(self): return self._get_pk_val() Skipping the hash function overhead. What would be the implications and consequences of this change? Since we know the pk is unique, wouldn't this serve the same purpose in terms of indexing? Why does Django need to hash the pk? -
Add static_appname_ to file name in Django
I deploy my first app on heroku but when I download some pdf file from app their names look like static_nameapp_namefile.pdf Help me to resolve this problem -
Django loop refactor: javascript script to views.py in Highcharts
I have a script running that works, but I want to move it to "views.py". I can't seem to get the data I need because of the loop Currently working script: <script> Highcharts.chart('movements_container', { chart: {type: 'column'}, title: {text: "{{account.name}} Income/Outcome"}, plotOptions: {column: {stacking: 'normal', dataLabels: {enabled: true}}}, tooltip: {pointFormat: "Current balance: {{account.balance}} DKK"}, yAxis: {title: {text: "Movements"}}, xAxis: {title: {text: "Income/Outcome"}, type: "datetime"}, credits: {enabled: false}, series: [ {name: "Balance", data: [{{account.balance|floatformat}}], stack: "balance"}, {% for movement in account.movements %} {name: "{{account.name}}", id: "account", data: [{{movement.amount|floatformat}},], stack: "expenses", tooltip: {pointFormat: "Date: {{movement.timestamp}}</br>Transaction: {{movement.text}} </br> Amount: {{movement.amount}}"}}, {% endfor %} ], }); </script> As you can see, the big block above with "series" is what I want to translate to views.py: 12 def account_details(request, pk): 11 assert not request.user.is_staff, 'Staff user routing customer view.' 10 9 account = get_object_or_404(Account, user=request.user, pk=pk) 8 7 chart = { 6 'chart': {'type': 'column'}, 5 'title': {'text': 'test'}, 4 'yAxis': {'title': {'text': "Movements"}}, 3 'xAxis': {'title': {'text': "Income/Outcome"}}, 2 'series': [ 1 # for movement in account.movements: 49 {'name': account.name, 'data':str(account.movements)} 1 ], 3 } 5 6 context = { 7 'account': account, 8 'chart': json.dumps(chart), 10 } 11 12 return render(request, 'bank/account_details.html', context) … -
Problem with importing new Mongo database into the server
I have a Django-based website on the server. I am not really professional at this btw! So, I started the website on the server showing some data from MongoDB. This time I would like to change the DB to the newer one. This is what I am doing: First I drop the last DB: (On venv): $ mongo <db_name> --eval 'db.aggregation__class.drop' Then I scr (the new db) JSON-exported file into a server directory. Then I call the mongo to activate that new db: $ mongoimport --db <new db name> --collection <new db collection name> --file <server directory> I also checked if the db is activated by this: $ mongo <new db name> --eval And it is working. The problem is when I am calling it in the views.py, it does not show that it is connecting to the new db. Consider the fact that it was working with the last db! views.py # connect to MongoDb Database myclient = MongoClient(port=27017) mydatabase = myclient[db_name] classagg = mydatabase['aggregation__class'] database_text = classagg.find() Any suggestion would be appreciated. Thanks -
Should i go with expressjs and mongoose or django and mongoose as the backend for my website (I'm using React for the frontend)?
I have been looking at tutorials for working in the backend of my website and our team members have also thought about using django since it comes with a lot of features(mainly giving permissions to different users is easy there) whereas i don't really have a clue about how this works using express with mongodb. Since the database used for our project is gonna be non-relational(i.e mongodb), please suggest me if i should go with express or django along with mongodb, any documents references will be much appreciated! -
django form not saving on postgresql but does save to sqlite
I've deployed the project to Heroku. I'm using postgresql for my database. The job is attached to a customer table using acct_no as the foreign key. I'm able to create customers using postgresql but I can't create a job. I'm able to create a job using sqlite but when i attempt to use the postgresql database, the createview does not create a job and redirects me to my homepage. I'm fairly new to django and I've tried looking for similiar questions on here but have not been able to find a solution. models.py class Jobs(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. acct_no = models.ForeignKey(Customers, on_delete=models.CASCADE, default=1000000, db_column='ACCT_NO') # Field name made lowercase. foreman = models.CharField(db_column='FOREMAN', max_length=45, blank=True, null=True) comments = models.CharField(db_column='COMMENTS', max_length=255, blank=True, null=True) # Field name made lowercase. views.py class JobCreateView(CreateView): model = Jobs template_name = 'new_job.html' form_class = JobForm def get_initial(self): initial = super(JobCreateView, self).get_initial() initial['acct_no'] = Customers.objects.get(pk = self.kwargs['pk']) return initial def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) customer = Customers.objects.get(pk = self.kwargs['pk']) context["customer"] = customer return context def get_success_url(self): return reverse_lazy('CustomerView', kwargs = {'pk':self.kwargs['pk']}) forms.py class JobForm(forms.ModelForm): class Meta: model = Jobs fields = ['acct_no', 'job_type', 'estimatedate', 'estimatetime', 'vacant', 'year_built', 'comments'] labels = { … -
Import "django.shortcuts" could not be resolved from source
Hello, I wanted to complete my projects that I did not work for a while due to my illness, but when I opened vs code, I came across such an error. -
Save WAV file in Django backend
I am trying to record a voice message in the frontend and send it to the Django backend to test it against a ML algorithm of voice gender prediction. In the frontend I record the voice and I use AJAX to send the blob to the backend where I try to use wave to save the file as a valid .wav. The problem is that the file that gets saved on the backend is only noise without hearing the voice at all. On the frontend I can listen to the voice recording just fine, sounding exactly as it should. I am wondering how could I save on the backend the blob that I receive as a valid WAV file? Here is the recording and blob sending logic on the frontend: <div> <div id='gUMArea'> <button class="home-btn" id='gUMbtn'>Request Stream</button> </div> <div id='btns'> <button class="home-btn" id='start'>Start</button> <button class="home-btn" id='stop'>Stop</button> </div> <div> <ul class="list-unstyled" id='ul'></ul> </div> <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script> 'use strict' let log = console.log.bind(console), id = val => document.getElementById(val), ul = id('ul'), gUMbtn = id('gUMbtn'), start = id('start'), stop = id('stop'), stream, recorder, counter=1, chunks, media; gUMbtn.onclick = e => { let mv = id('mediaVideo'), mediaOptions = { audio: { tag: … -
Django button click rendered View twice
i am really new with Django and still learning. I will try to explain my problem as well as possible. On a button click in my template i want to work with some values & variables: <form method='get' action=''> <input type="submit" value="{{ answer1 }}" name="btn1" /> <input type="submit" value="{{ answer2 }}" name="btn2" /> <input type="submit" value="{{ answer3 }}" name="btn3" /> <input type="submit" value="{{ answer4 }}" name="btn4" /> </form> my views.py: class MyView(TemplateView): def get(self, request, *args, **kwargs): obj = MyObject() self.create_dict(q_obj) if request.GET.get('btn1'): # some code... return render(request, self.template_name, { ... }) The Problem is now whenever i click the button, the used dictionary variable got replaced with the next one because there is a new rendering. [12/Jan/2022 21:48:46] "GET /quizapp/home/subject/ HTTP/1.1" 200 5267 {'answer': <Answer: 3>, 'correct': False} {'answer': <Answer: 5>, 'correct': False} {'answer': <Answer: 2>, 'correct': True} {'answer': <Answer: 7>, 'correct': False} [12/Jan/2022 21:48:47] "GET /quizapp/home/subject/round/ HTTP/1.1" 200 7864 {'answer': <Answer: 4>, 'correct': True} {'answer': <Answer: 2>, 'correct': False} {'answer': <Answer: 6>, 'correct': False} {'answer': <Answer: 1>, 'correct': False} i want to work with the first set but everything i change relates to the second dictionary. I tried fixing with some redirect commands but nothing works... i am … -
Django unittest run specific test syntax
I want to run one specific unit test from my app bank/tests.py in the pipeline but I keep getting errors, I believe I am missing something on the syntax here This is my test: class SettingsTestCase(TestCase): def test_timezone_default(self): target_timezone = 'Europe/Copenhagen' self.assertEqual(target_timezone, settings.TIME_ZONE) print("Test: Correct timezone") This is how I call the test in the pipeline: ... script: - echo "Unit test...." - python manage.py test bank/tests.py:SettingsTestCase.test_timezone_default ... This is the error message when the pipeline fails: RROR: bank/tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: bank/tests Traceback (most recent call last): File "/usr/local/lib/python3.10/unittest/loader.py", line 154, in loadTestsFromName module = __import__(module_name) ModuleNotFoundError: No module named 'bank/tests' ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1) Cleaning up project directory and file based variables 00:01 ERROR: Job failed: exit code 1 Any suggestions? -
error parsing UTF-8 params in Django app at Heroku
I have a django project running on Heroku dyno. The problem is that when I pass a query params in UTF-8 language (farsi) I got 500 error with this log message. 2022-01-12T22:11:30.432160+00:00 heroku[router]: at=info method=GET path="/api/memes/?search=%D8%AA%D8%B3%D8%AA" host=amindjangofirst.herokuapp.com request_id=dece8cd8-8a8e-489e-801a-6b1cbc3df270 fwd="184.163.35.204" dyno=web.1 connect=0ms service=83ms status=500 bytes=452 protocol=https 2022-01-12T22:11:30.431992+00:00 app[web.1]: 10.1.24.50 - - [12/Jan/2022:22:11:30 +0000] "GET /api/memes/?search=%D8%AA%D8%B3%D8%AA HTTP/1.1" 500 145 "https://amindjangofirst.herokuapp.com/api/memes/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" but if I use english characters in query everything works well also on my local machine it's working with UTF-8 params api is available at: working => https://amindjangofirst.herokuapp.com/api/memes/?search=test not-working => https://amindjangofirst.herokuapp.com/api/memes/?search=تست -
Module wsgi error when deploying Django app on apache
I had developped an application using Django (DRF). And I try to deploy it on a server. After following some tutorials on Internet, I got this error : mod_wsgi (pid=27182): Failed to exec Python script file '/my/django/project/path/myProjectName/wsgi.py'. mod_wsgi (pid=27182): Exception occurred processing WSGI script '/my/django/project/path/myProjectName/wsgi.py'. Traceback (most recent call last): File "/my/django/project/path/myProjectName/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application File "/my/django/project/path/venv/lib/python3.9/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/my/django/project/path/venv/lib/python3.9/site-packages/django/utils/version.py", line 1, in <module> import datetime File "/usr/lib/python3.9/datetime.py", line 12, in <module> import math as _math ModuleNotFoundError: No module named 'math' I had checked on some forums but I didn't find a solution to solve my problem. It seems that the problem comes from wsgi module, which is already installed when I was configure the server using this command: sudo apt install libapache2-mod-wsgi-py3 This is my V-host config: <VirtualHost *:8080> ServerAdmin webmaster@localhost # Available loglevels: trace8, ..., trace1, debug, info, no ErrorLog /my-django/project/path/error.log CustomLog /my-django/project/path/access.log combined ServerName my-domaine.com ServerAlias www.my-domaine.com DocumentRoot /my-django/project/path Alias /static /my-django/project/path/static <Directory /my-django/project/path/static> Require all granted </Directory> Alias /media /my-django/project/path/media <Directory /my-django/project/path/media> Require all granted </Directory> <Directory /my-django/project/path/myProject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /my-django/project/path/myProject/wsgi.py WSGIDaemonProcess django_app python-path=/my-django/project/path python-home=/my-django/project/path/venv WSGIProcessGroup django_app … -
Cannot reverse a Django migration using django-otp
Been trying to write the reverse code for a Django migration. Doing the migration there were no issues, but going backwards seems to be causing an issue. My migration file is below. from django.db import migrations, models def forward_migration(apps, schema_editor): totp = apps.get_model('otp_totp', 'TOTPDevice') # Doing some stuff with the devices def reverse_migration(apps, schema_editor): totp_device = apps.get_model('otp_totp', 'TOTPDevice') # Undoing some stuff with the devices class Migration(migrations.Migration): dependencies = [ ('project', 'MY_LAST_MIGRATION'), ] operations = [ migrations.RunPython(forward_migration, reverse_migration), ] When undo the migration, I get the following error: LookupError: No installed app with label 'otp_totp'. What doesn't make sense to me about this error is that if the app can't be found while undoing the migration, why were there no issues while doing the migration? The main solution to this category of problem according to SO is to check the settings.py and to ensure that the referenced app is there correctly. My INSTALLED_APPS: INSTALLED_APPS = [ ..., 'django_otp', 'django_otp.plugins.otp_totp', ... ] This would appear correct according to the django-top docs. I've also tried quite a few variants on the app_label input to get_model function and had no luck. Thank you all in advance! -
How to mock external API call inside a different request function DRF, python
In ViewSet in my DRF project: Let's say I have a post request in which I firstly get data from external api with requests.get, and then I serialize and return it as should be in post request. I am writing unittest with django unittest and I want to mock external api call. This is my first time with mock and I can't find such a case. To sum up: I have post function which gets data from external api if user hasn't passed something. I want to mock result of requests.get but I don't know how to implement it to test for post function I don't know If It would help you to get code snippets or my story is enough. If so, I can add it just let me know. Thanks to everyone that got through my story! -
Deploy failed Internal Server Error 500 - Heroku
I made a project in Django and I want to deploy in heroku but after performing this action it shows me the following error. The console does not show me errors, I attach test images. THANKS FOR READ. -
How low is the visibility of the model for the user?
How to make sure that only the creator of the model could see it, but other participants could not see it, that is, the person who created the model could only see it from his account, and from another account the person saw only his own I have a models.py model class Product(models.Model): username = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=254) image = models.ImageField(upload_to='media/', blank=True, null=True) company_name = models.CharField(max_length=100) def __str__(self): return self.username views.py class ProductListView(ListView): model = Product queryset = Product.objects.all() template_name = 'products_list.html' class ProductDetailView(DetailView): model = Product class NewProductView(LoginRequiredMixin,CreateView): template_name = 'product_form.html' model = Product form_class = NewProductForm success_url = reverse_lazy('product_list_page') class EditProductView(LoginRequiredMixin ,UpdateView): template_name = 'product_form.html' model = Product form_class = EditProductForm success_url = reverse_lazy('product_list_page') how to make it visible only to the current who created it, so that another user sees only his own model that he created. How do I limit the visibility of a model to its creator only? -
How to update changes in live website made with django?
There is an web application live in a server which is made with django. I need to alter a table of that application. I have the code and database in my local machine for working. I have altered the table and added two more columns in the local machine. Altering table in django gives error and you have to migrate the changes of the model. After that it is working fine in my local machine. But I don't know how to push this minor update to the live application. I have the remote access of the server. Do I just go the live project and edit the model code and save and make migrations using cmd? I am afraid I will do some kind of mistake and the application will be effected as it is live. I am new with server side stuffs. Please help. -
Why do I get an old data set in one case after a GET request, and an up-to-date data set in the other
I make a POST request, enter the data into the table, but after that I do a Get and get the old data in this case def get_queryset(self): transaction.commit() if self.action not in ['retrieve', 'list', 'create', 'selector']: res = self.queryset.filter(is_editable=True) else: res = self.queryset return res Up-to-date data) def get_queryset(self): transaction.commit() if self.action not in ['retrieve', 'list', 'create', 'selector']: res = self.queryset.filter(is_editable=True) else: res = Presence.objects.all() return res -
Django bulk update list of objects
I want to create an API endpoint, where you can PUT list of objects and it will work like this: If the ID is specified, query that object and try to update it (if no ID present, show an error) If no ID is present for an object, create. If any previous objects missing saved to the db missing from this list, delete it from the database. What I have found and did not work that way (most of them don't work at all): https://github.com/miki725/django-rest-framework-bulk https://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-update The example on django-rest site seems to do it like that, however it is not working for me. -
Which version of Django and/or Python is affected by IP Spoofing?
REF : https://portswigger.net/daily-swig/ip-spoofing-bug-leaves-django-rest-applications-open-to-ddos-password-cracking-attacks Reported Date: Jan 11 2022 Other than providing captcha, what security measure should be taken? Which version of Django and/or Python is affected by IP Spoofing? -
can't override django Form widget attributes correctly
I want to change the name of the widget but then i have two names inside the input class DocumentForm(forms.ModelForm): def __init__(self, *args, **kwargs): # to delete colon after field's name kwargs.setdefault('label_suffix', '') super(DocumentForm, self).__init__(*args, **kwargs) class Meta: model = Document name = "document" fields = ('id', 'comment', 'private', 'position', 'marked') # fields = '__all__' marked = forms.IntegerField( required=False, widget=forms.NumberInput( attrs={ 'name': "asdasdjasdasjdldsa", 'id': "device_documents___name___marked", 'class': 'check preview_image', 'onchange': 'cbChange(this)', 'mazen': "document_set-__name__-position" }, ) ) but if i print this i have two name name="marked" and name="asdasdjasdasjdldsa" how to delete the first one? print(f["marked"]) <input type="number" name="marked" name="asdasdjasdasjdldsa" id="device_documents___name___marked" class="check preview_image" onchange="cbChange(this)" mazen="document_set-__name__-position">