Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write Select If() in Django model object
Select IF(5>10, true, false); I want to write this using Django model. -
How to fix uWSGI internal routing?
I am closely following the uWSGI tutorial on offloading WebSockets and SSE. However, I have the issue that my Django worker cannot start up since uWSGI is not able to register the route. It is able to register it when I replace the socket of the SSE service with just a log call. I did make sure that the socket exists (I am using an emperor to start up both uWSGI configurations). I found this other StackOverflow question that suggested to enable PCRE support (which I already did). I do not get the warning about PCRE support anymore in my log file. I am trying different possibilities for two days now and I definitely need the help of someone with a fresh mind. This is my log when starting up the django worker (the sse worker is already started up): /usr/sbin/uwsgi --ini /usr/uwsgi/vassals.d/01_django.ini --die-on-term --need-app --plugin router_redirect [uWSGI] getting INI configuration from /usr/uwsgi/emperor.ini [uWSGI] getting INI configuration from /usr/uwsgi/vassals.d/01_django.ini unable to register route "equal:${CONTENT_TYPE};text/event-stream uwsgi:/tmp/sseapp.sock,0,0" command terminated with exit code 1 this is my 01_django.ini file: [uwsgi] socket = /tmp/django.sock chown-socket = nginx:nginx chmod-socket = 664 ; wait until the sse app is loaded wait-for-socket = /tmp/sseapp.sock ; configuring the … -
Accessing a dictionary using a key from another dictionary in Django template
I am passing two dictionaries to a Django template (reservations , prices) inside the template i have something like this: {% for key,value in reservations.items %} ... ... {% if value is False %} <div class="room"> <p class="room-id">{{ prices.{{ key }} }}</p> </div> {% else %} ... ... {% endfor %} now the problem is this line {{ prices.{{ key }} }} i am trying to evaluate the key value from the reservations dict to be used in the prices dict how this can be done? and thank you in advance. -
TypeError: 'ModelBase' object does not support indexing.
I created the models.py file and when I try to execute the 'makemigrations' command, I get the following error: return bool(self.related_name) and self.related_name[-1] == '+' TypeError: 'ModelBase' object does not support indexing I tried to find a forum reply, but the topics mainly concern the error that appears from the views.py file. In my situations, this file has not been created yet. Any help will be appreciated, also about the more transparent code in the database. My models.py from django.db import models #additives class TestUser(models.Model): name = models.CharField(max_length=50) class Trade(models.Model): all_trade_here = models.TextField() class ImageGallery(models.Model): image = models.ImageField() class SocialMediaLinks(models.Model): link = models.URLField() # Option for premium user class Prem_PhotoGallery(models.Model): name_photo_gallery = models.CharField(max_length=50) image_gallery = models.ForeignKey(ImageGallery, on_delete=models.CASCADE) class Prem_PDF(models.Model): name_pdf = models.CharField(max_length=50) file = models.FileField() class Prem_YouTube(models.Model): name_youtube = models.CharField(max_length=50) link = models.URLField() class Prem_VilmVeo(models.Model): name_vilmveo = models.CharField(max_length=50) link = models.URLField() class Prem_Audio(models.Model): name_audio = models.CharField(max_length=50) link = models.URLField() class Prem_Website(models.Model): name_website = models.CharField(max_length=50) link = models.URLField() class Prem_SocialMedia(models.Model): name_social_button_1 = models.CharField(max_length=50) links = models.ForeignKey(SocialMediaLinks, on_delete=models.CASCADE) class Prem_GoogleMaps(models.Model): name_google_maps = models.CharField(max_length=50) link = models.URLField() # element write by user class Person(models.Model): #basic information, all write user name = models.CharField(max_length=100) surname = models.CharField(max_length=100) phone = models.CharField(max_length=15) e_mail = models.EmailField(max_length=100) website = … -
Python I can't update blog in django
enter image description here enter image description here enter image description here enter image description here i can't update post in django, -
django url issue when trying to load ajax function
In urls.py i have a url like url(r^'level/(\d+)/ajax/reload/$', views.ajax_change_status, name='ajax_change_status'), I want to allow all ids between the level/*all ids/ajax/reload When im calling the ajax function it returns status 404, url not found.Now if i replace the (\d+) with any id like 1,23, it works.What could be the issue here? -
Create a symlink with setuptools
Django never came up with a standard way how to handle the configuration. Django puts it into the settings.py in the project directory by default which is not very practicable as you wouldn't want to overwrite a file in /usr/lib/python3/{site,dist}-packages/someproject/ to configure your project. Further the file would be gone after a package upgrade. I would like to package a django project in a way that works with at least sdist, bdist wheel and bdist deb on linux and includes/creates a symlink from /usr/lib/python3/{site,dist}-packages/someproject/settings.py to /etc/someproject/settings.py. This seems to be an impossible feat. The alternative would be to exec the settings in /etc/ which feels kinda dirty. -
Django Rest Framework: Display object only for specific choice
I've got this serializers: class PublicProgramSerializer(serializers.ModelSerializer): class Meta: model = Program fields = ( ... 'questions' ) questions = CustomQuestionSerializer(source="custom_questions", many=True) And: class CustomQuestionSerializer(serializers.ModelSerializer): class Meta: model = CustomQuestion fields = ( 'label', 'type', 'scope' ) Now the 'scope' is a choice field with 3 options: REGISTRATION, PARTICIPANT, EVENT and I want to serialize only custom questions where the scope is set to REGISTRATION. How can I achieve that? Thanks for any answer! -
Cache per object
I have a lot of users where every user can create a page. For example a user can add a custom color which is stored in the model. I don't want to clear the whole cache every time so I've added some helper functions to set a prefix for the keys. Is this the usual and good way to solve this problem? class Page(models.Model): # some fields ... # user # color # ... @property def _prefix(self): return f'{self._meta.object_name}_{self.pk}' def get_cache(self, key): cache.get(f'{self._prefix}_{key}') def set_cache(self, key, value): cache.set(f'{self._prefix}_{key}', value) def clear_cache(self, key): cache.delete(f'{self._prefix}_{key}') -
How to setup Python Development Environment and develop User login system
I am a PHP developer and now i am intrested in Python Development. I read lot of articles regarding "How to setup Python development Environment?".But all of them teach me to install python and run python program in terminal. My question is "How to setup DB and run python in browser". For Example("I am try to relate with PHP development"): For PHP development we just download XAMPP or WAMPP or Vagrant to setup an local Development Environment. After install XAMPP we just do our project in xampp/htdocs/project_name and create necessary project files. Then in browser just type: localhost/project_name to execute the project. And for DB we can use Phpmyadmin. Here what's my question is "How to do it for python?". What Software is required to setup Server and DB. After Installing the above required software.Where I need to do my project (Path to create project files). Then How to execute the project in browser. Where to create DB for the project. Sorry I surfed lot in internet and I only done installing Python 3.7 and run hello world! program on terminal. But I had no Idea to proceed further. Anyone please help me with right tutorial or article. Thanks in … -
Django Web Application with beautiful soup , request
I would like to have a website when user paste URL and they get all scrape data views in the website.. For now with this python3 code working fine via jupyter notebook from urllib.request import Request, urlopen as uReq from bs4 import BeautifulSoup as soup def make_soup(website) : req = Request(website,headers = {'User-Agent' : 'Mozilla/5.0'}) uClient = uReq(req) page_html = uClient.read() uClient.close() page_soup = soup(page_html, 'html.parser') return page_soup google_news_url = input('enter url') #https://www.google.com.my/search?q={}&source=Int&tbm=nws def forge_url (q): return google_news_url.format(q.replace(' ','+')) news_url = forge_url ('avengers') website = make_soup(news_url) headlines = website.findAll('h3') n = 0 for item in headlines : top = item.a #print(top) #print() text_headlines = top.text print(text_headlines) print() n +=1 Website development for python need Django and I already know basic Django. the website already run but where should I put this code? models.py? What should I put at views.py and google.html. Thanks ;) -
Django IndexError at / list index out of range
I was having problems migrating and when it finally worked this appeared on the home page. Some of the other pages work, and it seems to just be the home page. Error Messages: Internal Server Error: / Traceback (most recent call last): File "C:\Users\pc\formula_zone\lib\site- packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\pc\formula_zone\lib\site- packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\pc\formula_zone\lib\site- packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\pc\Downloads\formula_zone\mysite\racing\views.py", line 15, in racing_stats ra = races[0] File "C:\Users\pc\formula_zone\lib\site-packages\django\db\models\query.py", line 303, in __getitem__ return qs._result_cache[0] IndexError: list index out of range I think its on the views.py so here's that code as well. def racing_stats(request, race_id=None): drivers = Driver.objects.all().order_by('lap_time') races = Race.objects.all() for racer in drivers: driver_controller.update_race_time(racer) if race_id: ra = Race.objects.get(rac_id=race_id) else: ra = races[0] buttons = [] for r in races: buttons.append((r.rac_id, r.race_name)) context = { 'drivers': drivers, 'active_race': ra, 'buttons': buttons } return render(request, 'racing/racing_stats.html', context) def race_list(request): races = Race.objects.all() context = { 'races': races, } return render(request, 'racing/races.html', context) def race_detail(request, pk): race_ds = get_object_or_404(Race, pk=pk) print(race_ds) return render(request, 'racing/race_detail.html', {'race_detail': race_ds}) -
Postgresql Could not serialize access due to concurrent update, how to find out why
Project use Django and Postgresql 9.5. Sometimes I see the error in celery task. When object need change specified column it uses celery task. This task writes in separate table change history of an object and update column(not raw SQL, by Django ORM). Task write history by FDW extension into the foreign table. Thrown exception: Remote SQL command: COMMIT TRANSACTION\nSQL statement "SELECT 1 FROM ONLY "public"."incident_incident" x WHERE "id" OPERATOR(pg_catalog.=) $1 FOR KEY SHARE OF x"\n',) I can't take understand why it raises the exception. Task very simple screen logs(maybe it help): -
data manipulation in nested python dictionary
This is the list of dictionaries i have obtained from my previous function: [{'chapter1': [{'attended_right_percentage': 100.0, 'seq_no': '1'}, {'attended_right_percentage': 100.0, 'seq_no': '2'}, {'attended_right_percentage': 100.0, 'seq_no': '3'}, {'attended_right_percentage': 50.0, 'seq_no': '4'}, {'attended_right_percentage': 0.0, 'seq_no': '5'}]}], [{'chapter2': [{'attended_right_percentage': 100.0, 'seq_no': '1'}, {'attended_right_percentage': 100.0, 'seq_no': '2'}, {'attended_right_percentage': 100.0, 'seq_no': '3'}, {'attended_right_percentage': 50.0, 'seq_no': '4'}, {'attended_right_percentage': 0.0, 'seq_no': '5'}]}] now i want to fetch the data i.e; average of "attended_right_percentage" for each chapter -
Connect Django to MySQL ERROR "Did you install mysqlclient?"
I want Connect my Django Project To MySQL. I install mysqlclient already but when I migrate the project "python3 manage.py migrate" It has a bug!!! django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? I don't know how to fix it! please help me -
Restart the Django project and clear all metrics prometheus
i'm using django-prometheus. for Export Django metrics for Prometheus. When Django is running. Metrics work well. But when I upgrade Django and run runerver again. All the metrics are gone. And all information is erased! where is the problem from? -
Django + XAMPP on Mac (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")
Hi I am following this tutorial (https://www.youtube.com/watch?v=D6esTdOLXh4) to build a Django app with mysql. I am using XAMPP-VM for Mac. I set up my Database settings for Django as so: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangoproject', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '8080', } } And I have started mysql on XAMPP but when I run python manage.py migrate I get: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)") Thank you for your help! -
Use test database database for views testing
I am writing tests for my django application views and i am a beginner at this. I know that before running tests a new database is generated which only contains data that is being created at the time of running of tests but in my view's tests i am making API calls by url on my server which is using my default database not the test database in following way. def test_decline_activity_valid_permission(self): url = 'http://myapp:8002/api/v1/profile/' + self.profileUUID + '/document/' + \ self.docUUID + '/decline/' response = requests.post( url, data=json.dumps(self.payload_valid_permission), headers=self.headers, ) self.assertEquals(response.status_code, status.HTTP_201_CREATED) i want to know that if we can use test database for our testing our views or not. And what is difference between using request and using Client? -
How do I write a test to test this custom serializer for password reset?
Version: Django 1.11 Python 3.6 I am close to 100% test coverage and I got this custom serializer, which I am not sure how to write tests for. class PasswordResetConfirmSerializer(BasePasswordResetConfirmSerializer): def validate(self, attrs): self._errors = {} # Decode the uidb64 to uid to get User object try: uid = url_str_to_user_pk(attrs['uid']) self.user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): raise ValidationError({'uid': ['Invalid value']}) self.custom_validation(attrs) # Construct SetPasswordForm instance self.set_password_form = self.set_password_form_class( user=self.user, data=attrs ) if not self.set_password_form.is_valid(): raise serializers.ValidationError(self.set_password_form.errors) if not default_token_generator.check_token(self.user, attrs['token']): raise ValidationError({'token': ['Invalid value']}) return attrs How do I write a unit test for this serializer class? -
Django Application Lifecycle
What does exactly happen with Django application from request to response? I've read some docs online from which what I get is as follows- 1> When an API gets called request come to url.py. 2> Before or after middleware comes in part to do pre/post operations on request. 3> Then request forward to views.py. 4> If any data serialization/deserialization then request data gets passed to serializers.py. 5> Whatever response generated returned through middleware again. -
Django: Multiple models on the same table
I am building a recipe/cookbook application (something like cookpad or allrecipes) for a personal project. I have a model for image like so: class Image(Model): type = (("R", "Recipe"), ("P", "Profile"), ("E", "Embedded"), ("B", "Base")) name = models.CharField(max_length=55) type = models.CharField(choices=type, max_length=1, default="B") image = VersatileImageField( upload_to=FileNameGenerator(prefix="images"), placeholder_image=OnDiscPlaceholderImage( path=join(settings.MEDIA_ROOT, "images", "default.jpg") ), null=True, blank=True, ) I want to use one table only to store all image. But store it to different place for each different type. Example: Base image would be at images/xxx.jpg Profile's image at profiles/xxxx.jpg Recipe's image at recipes/xxx.jpg etc.. The only way I know how, is to make it an abstract model and extend it. But it would create many table (ProfileImage, RecipeImage, etc..) If I use proxy I cannot change/override the behaviour of image field. Is there a smart way to do this? -
How can we secure django python files for production release?
As we know python is interpreted language and we've to give it in readable format ? But how we can secure those files for production release so customer can't change it or modify it ? As like in Bin in C++, jar in JAVA and .exe in .Net We've referred Ans1 and Ans2 but it doesn't work for us. -
How to run django management custom commands with escalated privileges?
I am trying to run a custom django management command from my views. I have the view ready to execute the command as shown below: from django.core.management import call_command import django def send_queued_mails(): # Run Django Setup django.setup() call_command('send_all_queued_mails') But, when the command is executed on my windows machine, I get the following error: os.symlink(self.pid_filename, self.lock_filename) OSError: symbolic link privilege not held I can tackle this manually by running the terminal as Administrator but I want to run the command through my views and with escalated privileges. Any ideas or suggestions are appreciated. PS: I also tried using OS level command as shown below: from subprocess import call call(["python", "manage.py", "send_all_queued_mails"]) But I am getting the same error as above. -
docker-compose -f local.yml up not giving errors
Am trying to start a project with django-cookiecutter when i ran the docker-compose -f local.yml up i get this error -
Python Django : How to use LIKE while fetching data from mysql DB
I need a way to fetch similar records from DB using LIKE from Django . My code is : def fetchProductsDate1(request): query = request.session.get('query') date1 = request.session.get('date1') db = pymysql.connect(host=host,user=user,passwd=passwd,db=dbName) # Create a Cursor object to execute queries. cur = db.cursor() # Select data from table using SQL query. stmt = "SELECT FSN FROM tab WHERE query LIKE '%s' AND DATE(updated_at) LIKE '%s' " % (query.replace("'", r"\'"), date1) log.info(stmt) cur.execute(stmt) rows = cur.fetchall() json_data = rows[0][0] The db statement looks like: SELECT num FROM tab WHERE query LIKE 'soch sarees' AND DATE(updated_at) LIKE '2018-11-14' I want the statement to be like : SELECT num FROM tab WHERE query LIKE '%soch sarees%' AND DATE(updated_at) LIKE '2018-11-14' Any help will be really nice :) Thanks