Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Don't understand how my context variable is available wherease it is not passed in my view?
my question will seems to be very strange and many will think I have copy/paste code that I do not understand but this is not the case, it is my code that I refactor 2 weeks ago and when I read my code today I note what seems to be an error even if my app works well !!! As you can see in my views reallocate_edit method, I do not pass any context But in my template, I use a context variable patients that exist (I have my list of patients available in my template) this should not be possible? I did not understand to complete the explanation, in a previous code version, I actually pass a patients context def reallocate_edit(request): patients = [patient for patient in Randomisation.objects.all() if is_randomizable(patient.ran_num) and request.session.get('selected_site') in patient.ran_num] ... return render(request, 'randomization/reallocation_edit.html', {'patients': patients}) but I change using JS script to filter my select but JS code is also based on already existing patients list; even if I deactivate this JS code, it works views.py def reallocate_edit(request): if request.method == "POST": # reallocation = Randomisation.objects.get(ran_num = request.POST.get('patients')) patient = Randomisation.objects.get(ran_num = request.POST.get('patients')) # Réallocation d'un numéro de traitement au patient nouveau_medicament = reattribuer_medicament(patient.ran_num) … -
In Django CreateView use a class method to generate data to use in both get_context_data() and form_valid()
I'm actually working on a student project which i try to create a roguelike game on web using Python Django. I'm actully confusing by my issue, to explain what i need to do is generate random characteristics in a character creation impacted by a choosen character class . I want to send this characteristics to the user before he start the game. And use the characteristics I send him in my form_valid() to save the character in db. I know that I a can use get_context_data() to send some information to my template but I don't know if can use the data send by get_context_data() to the template in form_valid(). Actually I'm succed with the a CreateView to save a character with random characteristics by a choosen character class, see the code bellow. models.py class CharacterClass(models.Model): name = models.CharField(max_length=20, blank=True, null=True) minHpMax = models.PositiveIntegerField(default=10, validators=[MinValueValidator(10)], blank=False, null=False) minStrength = models.IntegerField(default=1, validators=[MinValueValidator(0)], blank=False, null=False) minAgility = models.IntegerField(default=1, validators=[MinValueValidator(0)], blank=False, null=False) minInt = models.IntegerField(default=1, validators=[MinValueValidator(0)], blank=False, null=False) minPhysResis = models.IntegerField(default=0, validators=[MinValueValidator(0)], blank=False, null=False) minMagRes = models.IntegerField(default=0, validators=[MinValueValidator(0)], blank=False, null=False) def __str__(self): return f'{self.id}: {self.name}' def generateHpMax(self): return random.randint(self.minHpMax, self.minHpMax + 10) def generateStrength(self): return random.randint(self.minStrength, self.minStrength + 10) def generateAgility(self): return random.randint(self.minAgility, … -
Why Bootstrap4 modal doesn't show data in my Django Template?
I'm trying to display data into the modal body with django variables. I'm very noob at ajax and django. The ajax function passes the id of the Galeria object and then the view returns a JsonResponse with the data. Why the modal is not taking the data? If I console.log it prints the data as well, but when I try to pass the data via django variables, the modal shows empty. What am I doing wrong? My views.py def get_galeria(request): galeria = Galeria.objects.get(id=int(request.GET['ajax_galeria'])) print(galeria.id) context = {} context['galeriaID'] = galeria.id context['galeriaNombre'] = galeria.nombre return JsonResponse(context, safe=False) models.py class Galeria(models.Model): uuid = models.CharField(unique=True, max_length=36, blank=True, null=True) usuario_creador = models.ForeignKey('Usuario', on_delete=models.CASCADE, db_column='usuario_creador', blank=True, null=True, related_name='galerias_usuariocreador') usuario_auditor = models.ForeignKey('Usuario', on_delete=models.CASCADE, db_column='usuario_auditor', blank=True, null=True, related_name='galerias_usuarioauditor') nombre = models.CharField(unique=True, max_length=100) ruta = models.ImageField(upload_to=settings.MEDIA_ROOT, unique=True, max_length=255) es_imagen = models.IntegerField() es_video = models.IntegerField() es_audio = models.IntegerField(blank=True, null=True) auditada = models.DateTimeField(blank=True, null=True) descripcion = models.TextField(blank=True, null=True) modificado = models.DateTimeField(blank=True, null=True) eliminado = models.IntegerField(blank=True, null=True) tipo = models.CharField(max_length=10, blank=True, null=True) grupo = models.ForeignKey('Grupo', on_delete=models.CASCADE, db_column='grupo', blank=True, null=True, related_name='galerias_grupo') fecha_creacion = models.DateField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.nombre class Meta: managed = True db_table = 'galeria' index.html (see ajax function and modal with id='modal_info_galeria') <!doctype html> <html lang="en"> <head> <!-- … -
DRF: ModelViewset only allows PATCH and OPTIONS
DRF ModelViewSet does not allow other HTTP methods. I am not sure why. I am trying to GET and later POST to an endpoint. However, the results show that it won't allow me. I want to allow all HTTP Methods for my endpoint. Here's the result: HTTP 405 Method Not Allowed Allow: PATCH, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Method \"GET\" not allowed." } Here's my code: #models.py class Batch(models.Model): request_time = models.DateTimeField(auto_now_add=True) email_to = models.EmailField(blank=True) captures = models.ManyToManyField(Capture) class Meta: verbose_name_plural = "batches" def __str__(self): form = "{} - {}".format(str(self.email_to), self.request_time.strftime("%Y-%m-%d %H:%M:%S")) return form #serializers.py class BatchSerializer(serializers.ModelSerializer): captures = CaptureManytoManySerializer(read_only=True, many=True) class Meta: model = Batch fields = '__all__' def to_internal_value(self, data): return data @transaction.atomic def create(self, validated_data): email_to = validated_data.pop('email_to') captures = validated_data.pop('captures') batch = Batch.objects.create( email_to=email_to) for capture_id in captures: capture = Capture.objects.get(capture_id=capture_id) batch.captures.add(capture) return batch #views.py class BatchViewSet(viewsets.ModelViewSet): serializer_class = BatchSerializer queryset = Batch.objects.all() #urls.py router = routers.SimpleRouter() router.register(r'batches', BatchViewSet, base_name='batch') urlpatterns += router.urls -
How to integrate 2 factor authentication with Google Oauth Login?
My Django web application is integrated with Google Oauth login. Even though I have enabled MFA for my email ID, I can log in to my website without confirmation for 2-factor authentication. I want to extend the Google OAuth login feature in my webapp by adding 2-factor authentication. Does google provide any APIs to achieve this? -
Add a prefix to primary key in django
I am trying to add a Prefix(YNT) to the primary key in django model Models.py class testmodel(models.Model): product_id = models.IntegerField(max_length=500, primary_key=True) product_short_code = models.CharField(max_length=500, default=0, null=True) How Can I do That ? also instead of starting the primary key from 1 can I start it from 1000 ? I want the table to look like this product_id product_short_code YNT1000 PP001 YNT1001 PL023 -
Do I really need Django Rest Framework to develop Restful api with Django?
I am learning Django to develop api, but I find that most of the tutorials on the web are all use Django Rest Framework. Does it really need this framework to develop restful apis? Can I develop restful apis without Django Rest Framework -
mysqlclient install in python3 on mac os
install mysqlclient in python3 system this error command pip3 install mysqlclient error: ERROR: Command errored out with exit status 1: command: /usr/local/opt/python/bin/python3.7 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/tj/vjwl0qpd6l5ct6bdjgwyk1rh0000gp/T/pip-install-abwz3tky/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/tj/vjwl0qpd6l5ct6bdjgwyk1rh0000gp/T/pip-install-abwz3tky/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/tj/vjwl0qpd6l5ct6bdjgwyk1rh0000gp/T/pip-install-abwz3tky/mysqlclient/pip-egg-info cwd: /private/var/folders/tj/vjwl0qpd6l5ct6bdjgwyk1rh0000gp/T/pip-install-abwz3tky/mysqlclient/ OSError: mysql_config not found ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Serializers in spring boot
Django has a rest-framework that allows you to easily create multiple serializers for one entity and then use them. Is there a feature in spring boot (or some kind of dependency) that makes it easy to make your serializers as well? Entity for Example class User(models.Model): username = models.CharField(max_length=20) email = models.CharField(max_length=20) password = models.CharField(max_length=20) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) Like this, I can make two serialisers for one entity in django class FooUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'id', 'username', 'email', 'password', 'first_name', 'last_name', ) class BarUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'username', 'first_name', 'last_name', ) And use this def list(self, request, *args, **kwargs): return Response(FooUserSerializer(instance=request.user).data, status.HTTP_200_OK) -
How efficently change fetched data from django raw query
For my project, I needed to run a raw query to increase performance. The problem is here that for one part I need to change value of fetched data to sth else(gregorian date to jalali) and this causes my performance to decrease a lot. cursor.execute("select date,number from my_db) while True: row = cursor.fetchone() if row is None: break data.append(row) This section longs about 1 min for 4 million data, but I need to chanfe date like this: cursor.execute("select date,number from my_db) while True: row = cursor.fetchone() if row is None: break row = list(row) row[0] = (jdatetime.datetime.fromgregorian(datetime=row[0]).strftime( '%y/%m/%d, %H:%m')) data.append(row) this causes my code to run in 7 min. I wonder if there is a way to do this change efficiently -
Django app returns 404 when deployed with NGINX
I am trying to deploy my django app to a server(nginx+uWSGI). However when I uwsgi --ini djangoapp.ini and access https://example.com/blah1/blah2/admin/ I get a 404. If I run my app locally it returns the admin page. Is there sth that I am missing? My default.conf upstream django { server unix:///home/me/djangoapp/djangoapp.sock; } server { listen 8000; server_name example.com; location / { root /usr/share/nginx/html; index index.html index.php index.htm; } location /blah1/blah2/ { alias /home/me/djangoapp; uwsgi_pass django; include /home/me/djangoapp/uwsgi_params; } Any help is appreciated. -
django.db.utils.IntegrityError: Problem installing fixture
I'm attempting to create a fixture from my development database data and storing it my test database. This data happens to be only one model. I ran the dumpdata command as such: python manage.py dumpdata minerals.mineral --all --indent=4 --output=minerals/test_minerals/fixtures/test_mineral_data.json When attempting to run the python manage.py test, the following error is raised: django.db.utils.IntegrityError: Problem installing fixture '../minerals/test_minerals/fixtures/test_mineral_data.json': Could not load minerals.Mineral(pk=872): UNIQUE constraint failed: minerals_mineral.name https://docs.djangoproject.com/en/2.2/topics/testing/tools/#django.test.TransactionTestCase.fixtures By default, fixtures are only loaded into the default database. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I was under the initial impression that fixtures were stored in an empty database when attempting to unit test but apparently that is incorrect? What can be done to emulate the data so I can test? tests.py class SearchFormResults(TestCase): fixtures = ['minerals/test_minerals/fixtures/test_mineral_data.json'] def test_user_search_query_fail(self): response = self.client.get( reverse("minerals:search_list"), data={'query': 'Kryptonite'}, HTTP_REFERRER=reverse( "minerals:letter_list", kwargs={'query': 'N'} ), follow=True ) models.py class Mineral(models.Model): name = models.CharField(unique=True, max_length=255) image_filename = models.ImageField(max_length=255, blank=True) image_caption = models.CharField(max_length=255, blank=True) category = models.CharField(max_length=255, blank=True) formula = models.CharField(max_length=255, blank=True) strunz_classification = models.CharField(max_length=255, blank=True) crystal_system = models.CharField(max_length=255, blank=True) unit_cell = models.CharField(max_length=255, blank=True) color = models.CharField(max_length=255, blank=True) crystal_symmetry = models.CharField(max_length=255, blank=True) cleavage = models.CharField(max_length=255, blank=True) mohs_scale_hardness = models.CharField(max_length=255, blank=True) luster = models.CharField(max_length=255, … -
How does Django store it's staicfiles after collectstatic is run?
I need a bit of clarification regarding how Django updates its static files. Here is a hypothetical that will explain my predicament: I'm working on my own website which requires a link to a PDF that is stored as a static file. Later I replaced this PDF file, with a slightly altered name, and made corrections respectively in my code. Then I run the collectstatic command to replace the old static files and everything works as expected. Explorer shows me that the old files have been properly replaced in their respective folders. When I go to test the link I'm still forwarded to my old PDF file. The old staticfile as if nothing has been replaced. Can anyone explain to me how this happened? I'm just concerned and a bit freaked out that my old static file is still being referenced. I mean it could just be a simple typo or I have a haunted static folder on my hands. -
Django redirects when accessing admin page
I have deployed my django app on a server(nginx + uWSGI). However when I run python3 manage.py runserver 7500 and curl http://127.0.0.1:7500/admin/ I get a "GET /admin/ HTTP/1.1" 302 0. If I uwsgi --ini app.ini and access https://example.com/blah/blah/admin/ from browser I get a 404. urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), #REST FRAMEWORK URLS ] default.conf server { listen 8000; server_name example.com; location / { root /usr/share/nginx/html; index index.html index.php index.htm; } location /blah/blah/ { alias /home/me/DjangoApp; uwsgi_pass django; include /home/me/DjangoApp/uwsgi_params; } Any help is appreciated. -
How to create unique and composite index on django model using mongo db
I'm using djangi and have created one model Person with few fields and want to implement indexing for efficient results. I've done indexing on SQL but with mongoengine I'm doing for first time. I'm stuck on how to implement unique index on the name column and also how to implement a composite index on phone_number and email fields. Thanks for the help from mongoengine import Document, fields class MongoDocument(object): def __unicode__(self): return unicode_class(self) def to_dict(self): return convert_to_dict(self) class Person(Document, MongoDocument): name = fields.StringField(max_length=250) phone_number = fields.StringField(max_length=10) email = fields.StringField(max_length=250) active = fields.BooleanField(default=True) -
HTTP Error 404: Not Found during LinkedIn social login
I have changed the all the requirements using below link where i changed to v2 api migration but when its time for retriving the linkedin data its throwing the above error. Linkedin v2 migration -
Django: Computing average using javascript
How to compute grades in dynamic table using JavaScript I will demo first the system works if the teacher click the button (Insert New Cell) it will display New Cell for example the teacher click 4times the button it will look like this if the teacher put the grades in the textbox the result will automatic display in the average <table id="blacklistgrid"> <tr id="tr"> <th id="th">Students Name</th> <th>Average</th> </tr> {% for student in teacherStudents %} <tr id="tr2"> <td id="td">{{ student.Students_Enrollment_Records.Student_Users }}</td> </tr> {% endfor %} </table> <button type="button" value="" class="save" onclick="doTheInsert()" title="Insert New Cell" id="save">&plus;&nbsp;Insert New Cell</button> <button type="button" value="" class="save" onclick="undoTheInsert()" title="Undo Recent Action" id="unsave">&times;&nbsp;Undo Recent Action</button> <script> function doTheInsert(){ let header=$("tr#tr"); // same as $.find("tr[id='tr2']") $('#th').after("<th data-id='header' id='header'><input type='date'></th>"); let rows=$("tr#tr2"); rows.append("<td data-id='row' id='newRows'><input type='text' name='needtocompute' id='number' /></td>"); } </script> can you guys fix my code ? -
Django redirects admin page when deployed
I have deployed my django app on a server(nginx + uWSGI). However when I run python3 manage.py runserver 7500 and curl http://127.0.0.1:7500/admin/ I get a "GET /admin/ HTTP/1.1" 302 0. The strange part is that if I run and access my admin locally I am able to access it. urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), #REST FRAMEWORK URLS ] Any help is appreciated. -
How to get JSON Response for Sign Up Form in Django
I am running a website using Django and i am new to it.Here is my code: views.py: def signup(request): registered = False failed_ref = False wrong_ref = False user_err = '' mobile_err = '' if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = ProfileForm(data=request.POST) if 'city' in request.POST: if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'image' in request.FILES: profile.image = request.FILES['image'] print(request.POST) profile.save() try: ref_con = profile.referral_contact if ref_con == profile.mobile_no: failed_ref = True elif ref_con == Profile.objects.get(mobile_no=ref_con).mobile_no: prof = Profile.objects.get(mobile_no=ref_con) wallet_rec = Wallet.objects.get(profile=prof) wall = Wallet.objects.get(profile=profile) registered = True except Profile.DoesNotExist: wrong_ref = True data = {'registered': registered, 'failed_ref': failed_ref, 'wrong_ref': wrong_ref} return JsonResponse(data) else: print(user_form.errors, profile_form.errors) user_err = '' mobile_err = '' if user_form.errors: user_err = "A profile with this username already exists!" if profile_form.errors: mobile_err = "A profile with this mobile number already exists!" data = {'registered': registered, 'failed_ref': failed_ref, 'wrong_ref': wrong_ref, 'user_error': user_err, 'profile_error': mobile_err} return JsonResponse(data) else: user_form = UserForm() profile_form = ProfileForm() return render(request, 'accounts/profile_form.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered, 'failed_ref': failed_ref, 'wrong_ref': wrong_ref}) My question is how to get response in JSON for this function. I have tried ,but it not able to … -
Django multiple annotate slows down the query
I have been debugging with django debug_toolbar, if I use more than one annotate query then it takes a lot of time for Django query to fetch the query results. class Project_First(models.Model): project_first_results_M2M = models.ManyToManyField(Project_First_Results) class Project_Second(models.Model): project_second_results_M2M = models.ManyToManyField(Project_Second_Results) class Project(models.Model): project_first_M2M = models.ManyToManyField(Project_First) project_second_M2M = models.ManyToManyField(Project_Second) I m trying to count all the objects present in project_first_results_M2M of all the project_first_M2M objects. ie, let's suppose, project_first_M2M has 3 objects of Project_First and I want to count all the total project_first_results_M2M objects present in all 3 of them. Project.objects.all().annotate(first_res_count=Count('project_first_M2M__project_first_results_M2M',distinct=True)) Above Query works fine and would take 80ms to fetch the results. But problem occurs when i try to add an additional annotate to query. Project.objects.all().annotate(first_res_count=Count('project_first_M2M__project_first_results_M2M',distinct=True)).annotate(second_res_count=Count('project_second_M2M__project_second_results_M2M',distinct=True)) This would take almost 4000ms to fetch the results. Both project_second_M2M and project_first_M2M contains the same fields and the same number of objects. I even tried in vice-versa condition to the above query and query slows down only when I add additional annotate. Is there any fast and alternate solution to achieve the same in much efficient way? maybe with raw sql queries. I want to count all the objects of project_first_results_M2M of all project_first_M2M objects within each Project object and similarly for project_second_results_M2M -
How to express one-to-many in Django and use append and remove?
class Player(models.Model): owner = models.ForeignKey('self',blank=True, null=True,related_name = "player_owner") slaves = models.ManyToManyField('self',blank=True, null=True) I want to define a Player model, whose instance can have its slaves composing by other players;at the same time it could be a slave of other player. How to define the slaves field and manipulate it in terms of an instance? -
Django template not rendering on webpage
Directory structure -> https://i.stack.imgur.com/oNtk6.png mainx.html (mysite\personal\templates\personal\mainx.html) ... <body> <h1>Hello There</h1> <div> {% block content %} {% endblock %} </div> </body> ... home2.html (mysite\personal\templates\personal\home2.html) {% extends "personal/mainx.html" %} {% block content %} <p>Hey! Welcome to my website! Well, I wasn't expecting guests. Um, my name is Harrison. I am a programmer.</p> {% endblock %} Setup : Installed Django using pip install > created project > created app > configured n wrote html files Why it is not rendering the template paragraph text? -
I don't enter pass for postgre sql in cmd on windows
I don't enter pass for postgre sql in cmd on windows. I should be enter a pass for psql.but i is typing,no thing is typed!!! My keyboard is health.but at time of enter pass,no thing is not entered! -
Looking to make a mobile app version of a web app I build with Python/Django, where should I start?
I've built a web app that was designed for small businesses to use to manage tasks, projects and sales. I'm a relatively new programmer, and I only really have experience with Bootstrap, Python and Django. Mobile app development is something new to me, and I'm planning to hire someone to assist me with this, and at the same time try to learn myself. Any suggestions/comments/ideas as to where I should begin? Do you think an app like this could be built using Flutter? Any challenges I should consider? -
Rich Text Field not returning desired output
I'm using CKEditor rich text field for my Django blog app. But not getting the desired output. If I write some heading text, on the front end the output is <h1> Hello </h1>. But I don't want heading tags, I also tried to striptags but in that case, the output is not heading it is simple paragraph text index.html {% for posts in post %} <div>{{posts.content|striptags}}</div> {% endfor %} Rich text model content = RichTextField(blank = True ,null = True)