Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: reference relationship in fixture using unique key(s)
Let's say I have the following database models: class Team(models.Model): name = models.CharField(max_length=50, unique=True) class Player(models.Model): name = models.CharField(max_length=50, unique=True) team = models.ForeignKey(Team, on_delete=models.CASCADE) I'm creating a fixture to load initial data into these tables, which looks like this: # TEAMS - model: load.team fields: id: 1 name: Raiders # PLAYERS - model: load.player fields: team: 1 name: Derek Carr - model: load.player fields: team: 1 name: Darren Waller This works fine, but I'd like to reference team by its unique column name (for a more human readable file), so the player fixtures would look like this: # PLAYERS - model: load.player fields: team: Raiders name: Derek Carr - model: load.player fields: team: Raiders name: Darren Waller Is there anyway to do this, besides setting Team.name as the primary key? -
is there any possibility to provide an alternate db server in django?
is there any possibility to provide an alternate db server in django, so in case if my one db server goes down, it can fetch data from alternate db server and once connection gets back it starts using the primary db server. -
Convert response.text to a dictionary in python
I have an API which gives me the following data in response.text, How can I caonvert this data into a python dictionary? response.text [{"_id":"5dccedadff47e867a2833819","tel":"XXXX","loc":[28.498692,77.095215],"tripId":"5dccedaaff47e867a28337ec","mode":"automated","osm_data":{"distance_remained":10791,"time_remained":1649.5},"distance_remained":10870,"time_remained":1173,"curr_ETA":"2019-11-14T06:43:19.664Z","address":"100, The National Media Centre, Sector 24, Gurugram, Haryana 122022, India","city":"Gurugram","createdAt":"2019-11-14T06:01:17.166Z"},{"_id":"5dccedacff47e867a2833801","tel":"XXXX","loc":[28.498692,77.095215],"tripId":"5dccedaaff47e867a28337ec","mode":"automated","osm_data":{"distance_remained":10791,"time_remained":1649.5},"distance_remained":10870,"time_remained":1173,"curr_ETA":"2019-11-14T06:43:18.459Z","address":"100, The National Media Centre, Sector 24, Gurugram, Haryana 122022, India","city":"Gurugram","createdAt":"2019-11-14T06:01:16.163Z"}] I wanto access the data in this response.text as a dictionary -
Set_password function of django is not working
I am saving this details in custome table(MYSQL) , but password is not getting encrypt,password save in plain text. def regauth(request): if request.method == "POST": form = UserAuth(data=request.POST) # user_form = UserAuth(data=request.POST) if form.is_valid(): try: messages.info(request, 'inside try') user = form.save() user.set_password(form.password) user.save() return redirect('login_url') except: messages.info(request, 'inside exception') return render(request, 'registration/registration.html', {'form': form}) else: user_form = UserAuth() return render(request, 'registration/registration.html', {'form': user_form}) Forms.py class UserAuth(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = RegAuth fields = "__all__" -
django project: template having node_modules which i can not find in static folder
I downloaded an example template and want to use in django project. my all static files is in static folder, settings.py modified accordingly, but I'm facing problem in line <link rel="stylesheet" href="{% static 'node_modules/mdi/css/materialdesignicons.min.css' %}"> after executing <link rel="stylesheet" href="/static/node_modules/mdi/css/materialdesignicons.min.css"> this given path is not present in my static folder. I don't have idea about node.js. Can you tell me how my html page will look exactly what i downloaded. right now it is not loading any supporting file from static -
Runing custom script (to populate model from CSV) from admin page
I am quite new to django and need help and ideas finding right way to do it. In short I have model which is populated few time a year from a CSV file (deleting all info and replacing it by new form file). To do that - I wrote script which is run from shell. It works, but not convenient and I cannot let to do it someone else. I would like to upgrade and make that script callable from admin page. This is what got so far: To upload CSV file I created model for it (in models.py): class DrgDuomenys(models.Model): drg_duomenys = models.FileField(upload_to='DRG_csv/') data = models.DateField(auto_now=False, auto_now_add=True) Model which should be populated (also in models.py): class DRGkodas(models.Model): drg_kodas = models.CharField(max_length=4) drg_koeficientas = models.DecimalField(max_digits=6, decimal_places=3) drg_skaicius = models.IntegerField() def __str__(self): return self.drg_kodas Old script (named ikelti_drg.py) for populating model, activated from shell by writing py manage.py ikelti_DRG --path path/to/your/file.csv import csv from django.core.management import BaseCommand from stv.models import DRGkodas, DrgDuomenys class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('--path', type=str) def handle(self, *args, **kwargs): path = kwargs['path'] with open(path, 'rt') as f: reader = csv.reader(f, dialect='excel') for row in reader: drg_kodai = DRGkodas.objects.create( drg_kodas = str(row[0]), drg_koeficientas = float(row[1]), drg_skaicius = int(row[2]), ) … -
Django Error: user_register_model matching query does not exist
How to fix This Error I'm Trying To Fix This Error But I Get Again And Again i want to detect user but when i write the code down below i get this error Any Help Will Be Appreciated! ERROR user_register_model matching query does not exist. Here is my Views.py def buy_form(request): if request.method == 'POST': usr_buy = user_buy_form(request.POST) if usr_buy.is_valid(): usr_buys = usr_buy.save(commit=False) user_register_obj = user_register_model.objects.get(user=request.user) usr_buys.users = user_register_obj usr_buys.save() else: return print(usr_buy.errors) else: usr_buy = user_buy_form() context = {'usr_buy':usr_buy} return render(request,'user_buy.html',context) Here is my Models.py class user_buy(models.Model): users = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=200) payment_method = models.CharField(max_length=500) price = models.IntegerField() Trade_limits = models.IntegerField() Location = models.CharField(max_length=1000) def __str__(self): return self.users.user.username Here is my Forms.py class user_buy_form(forms.ModelForm): class Meta(): model = user_buy fields = '__all__' exclude = ('users',) Here is my user_buy.html {% extends 'base.html' %} {% block body_block %} <form class="form-control" method="POST"> {% csrf_token %} {{usr_buy.as_p}} <input type="submit" class="btn btn-primary" value="Submit"> </form> {% endblock %} -
OperationalError: (1049, "Unknown database 'test_db_14'")
When executing django tests using parallel command Im facing the above error. Im using MySQL 5.6 for test db. -
How to store data structures when certain operations need to be performed in faster than O(n) time?
(I'm a newcomer to databases, so apologies if this is a strange question. Feel free to disagree with my point of view if you think I'm not thinking clearly.) Some data structures have support for operations that can be completed in better than O(n) time, where n is the number of items currently stored in the structure. For example, heaps allow for O(log n) insertion and deletion of items. I don't understand the correct way to store such data structures inside a database. Question. In regards to databases in general, and in regards to Django 2.2.7 and Postgres 12.0 specifically, what is the correct way to store data structures when faster than O(n) operations are required? The remainder of this question is elaboration and discussion. Suppose, for example, that our database consists of two tables, one called Person and one called Task. Each Task has an associated Person field called assignee representing the person to whom the task was assigned, and an associated int field called priority representing the urgency of the task. Now any given person in the real world might we might want to query the database for the highest priority Task that they've been assigned. The simplest … -
How Get data with join django Rest framework from other table
I have two models first one is class Event(models.Model): main_image = models.ImageField(upload_to='events/images', default="") event_name = models.CharField(max_length=100, default="") event_organizer = models.ForeignKey( Organizer, on_delete=models.CASCADE, limit_choices_to={'is_active': True}) and other one is class additional_images(models.Model): # When a Event is deleted, upload models are also deleted event = models.ForeignKey(Event, on_delete=models.CASCADE) image = models.FileField(upload_to='events/images', null=True, blank=True, default="") and serializer class is given by class eventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ['id', 'main_image', 'event_name', 'event_address', ''event_organizer'] my question is how i get additional_images with eventSerializer. -
How to create an architecture in Django which enables user-installable third-party plugin integration
How to create an architecture in Django which enables user-installable third party plugin integration Problem: We need to create a Django project which enables third-party developers to develop plugins. The Django application is just acting as a RestAPI/socket server for now and has a react application on the frontend. We certainly need to create some frontend hooks for the UI part for the plugin to be intractable. Other concerns: - We want to host the plugin ourselves by some kind of installation processes like copying files or running setup of some kind etc. - We don't want the plugin to have direct access to the database - We want the plugin to be an event driven code, ex: if the happens then some part of code will run - We want the plugin to have their own data to be saved in our database - We want the plugin to be safe on our system so that they can't access our system files - We don't want plugin execution to slow our current process and view it should run in the background if possible. Our stack: - Django (with some part on django-channels) - React (A PWD) - Celery with … -
Bootstrap Auto-complete Error: Cannot read property " " of undefined
I m trying to use Bootstrap autocomplete, with Django .. I Tested the calls and the ajax request sent successfully to my views, but i did not get response in my field .. due to an error appeared in the console of type: Uncaught TypeError: Cannot read property 'updatedItem' of undefined The Error Appears multiple times with different names alternative to 'updatedItem' ... What I M Missing Here Please! views.py def SearchMedical(request): results_pharmacy = None if request.GET.get('q'): q = request.GET['q'] results_pharmacy = PharmacyDetails.objects.filter(name__istartswith = q).values_list('name',flat=True) json = list(results_pharmacy) return JsonResponse(json, safe=False) search.html <script src="https://cdn.jsdelivr.net/gh/xcash/bootstrap-autocomplete@master/dist/latest/bootstrap-autocomplete.min.js"></script> <form method="GET" action="{% url 'searchMedical' %}" id="searchMedical"> <input class="basicAutoComplete form-control rounded-0" autocomplete="off" type="text" placeholder="Pharmacy name"> </form> <script> $('.basicAutoComplete').autoComplete({ resolverSettings: { url: '{% url "searchMedical" %}' }, minLength: 1 }); </script> -
Django: Pass filter to custom QuerySet
Is there a way to pass _filter to the QuerySet Manager as I try here? Currently, I always receive the error message too many values to unpack (expected 2). def get_super_guests(self): _filter = "answers__choices__answer='Very disappointed', answer_NPS__gte=9" return Response.objects.get_super_guests(self.request.event.pk, _filter) class ResponseQuerySet(models.QuerySet): def get_super_guests(self, event_pk, _filter): return ( self.filter( survey__event=event_pk, survey__template=settings.SURVEY_POST_EVENT, answers__question__focus__in=[ QuestionFocus.FEELING_ABOUT_ATTENDING_AGAIN, QuestionFocus.RECOMMENDATION_TO_FRIENDS, ], ) .annotate( answer_NPS=Case( When( answers__question__focus=QuestionFocus.RECOMMENDATION_TO_FRIENDS, then=Cast( 'answers__answer', output_field=IntegerField() ) ) ) ) .filter( _filter ) ) -
Save data of an increasing dictionary in django
I am trying to save the data of an API response in my django tables but the problem that I am facing is that the API responds in a list which consists of several dictionaries and the number of dictionaries increase everytime i call the api. Example On 1st call A = [{foo:4, bar:5}] On 2nd call A = [{foo:4, bar:5}, {foo:8, bar:10}] On 3rd call A = [{foo:4, bar:5}, {foo:8, bar:10}, {foo:12, bar:15}] and so on My model looks like this: class Tracking(models.Model): foo = models.CharField(max_length=255, default=0) bar = models.CharField(max_length=255, default=0) My views.py class trackapi(APIView): def get(self, request, pk): response = requests.request('GET', url, headers=headers, data=payload, auth=user_pass) for i in response.text: Tracking.objects.create(foo = i["foo"], bar = i["bar"] But this will create a lot of multiple enteries in the tables, how should I do this such that data in my table is not replicated ? -
Is it possible to open Labelimg in Angular with python backend?
I want to use the image labeling python tool "LabelImg" in a browser with angular as front-end. Is it possible to do that?. If no , then how can labeling an image is done using angular so that the pixel values selected for each box in that image is set to back-end? -
How to slove django-pure-pagination errors?
i using github opensource library ---- django-pure-pagination ,Padding.... now ,it make errors. i don't know slove it. enter image description here enter image description here this is error! This is my code: please help me , i don't know how to solve it. thansk friends. -
Return sorry / busy HTML page for particular page if got intensive access on that page
Thinking of returning static busy / sorry html template with 200 response when we got intensive accesses on that particular page. This response needs to be HTTP 200 if we return from our EC2 apache instance to pretend the instance is healthy. 503 would be preferable if we can return this static template BEFORE our apache, say, in Elastic Bean Stalk level.. -
I want to get some fields from the diferents table, whith django rest framework for Andgular 8
i want to do a queryset to get some fields from different tables and send it like a .json I hope that the output of the program is like the following: { "id":"1", "nombre": hamburgesas "estado": terminado, "fecha":14/11/2019 } this is my models.py from django.db import models class categorias(models.Model): id_categoria = models.AutoField(primary_key=True) nombre = models.CharField('Nombre de la categoria',max_length=100, blank=False, null=False) class Meta: verbose_name = 'Categoria' verbose_name_plural = 'Categorias' def __str__(self): return self.nombre class productos(models.Model): nombre = models.CharField(max_length=100, blank=False, null=False) descripcion = models.CharField(max_length=500, blank=False, null=False) #img = models.CharField(max_length=500, blank=False, null=False) precioVenta = models.DecimalField(max_digits=9, decimal_places=2) id_cate = models.ForeignKey(categorias, on_delete = models.CASCADE) class Meta: verbose_name = 'Producto' verbose_name_plural = 'Productos' def __str__(self): return self.nombre class Estado(models.Model): id_estado = models.AutoField(primary_key=True) estado = models.CharField('Estado de producción',max_length=100, blank=False, null=False) def __str__(self): return self.estado class Pedido(models.Model): id_ped = models.AutoField(primary_key=True) fecha = models.DateTimeField(auto_now_add=True) id_prod = models.ForeignKey(productos, on_delete = models.CASCADE) id_est = models.OneToOneField(Estado, on_delete = models.CASCADE) class Meta: unique_together = ("id_prod", "id_est") ordering = ['fecha'] verbose_name = 'Pedido' verbose_name_plural = 'Pedidos' def __str__(self): return self.id_ped This is my serializers.py from rest_framework import serializers from apps.productos.models import productos, Pedido, Estado from django.contrib.auth.models import User class EstadoSerializer(serializers.ModelSerializer): estado = serializers.CharField() class Meta: model = Estado fields = ('estado', 'id_estado') class ProductoSerializer(serializers.ModelSerializer): … -
How to create dynamic table in django forms
Any one help me out to create dynamic table in django forms onclick add button need to get new row and automatically summing-up the price column and all row data to insert into mysql database table of multiple rows when submit django form -
How to save a message body of an email?
how to save the message body, so that it can be used to display any other page!! I am using Django, HTML I have a .html page compose_mail.html, in which there are fields like: - TO: (reciever's email address) - Title - Message Body (WYSIWYG Editor) - send button Now, i have another html page, mail_details.html with fields: - Send To: (Reciever's Email Address) - Message Body: (WYSIWYG Editor) I want to save the message body in database or any folder and use that reference to see my sent mails body in mail_details.html page. if i save this body message as a text in database-table-column than any large size message cannot be saved. as the email message body consists of formatted text, image, url, any type of text font and much more. Please help me out in this problem statement. -
How to query an object through its foreignkey? django
This is my model, which has a foreignkey of User model. class StudentGrade(models.Model): PERIOD_CHOICES = [ (1, 'First Grading'), (2, 'Second Grading'), (3, 'Third Grading'), (4, 'Fourth Grading'), (5, 'First Semester'), (6, 'Second Semester') ] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, limit_choices_to=Q(is_student=True)) period = models.PositiveSmallIntegerField(choices=PERIOD_CHOICES) subject = models.ForeignKey(Subject, on_delete=models.DO_NOTHING, null=True,) grade = models.DecimalField(max_digits=4, decimal_places=2) and in my views.py I need to get the specific object of StudentGrade thourgh its User. here is my views.py : def StudentGrade(request, id): student = StudentGrade.objects.get(user__user_id=id) context = { 'student': student, } return render(request, 'student_dashboard/student_grade.html', context) with these codes i am getting an error : AttributeError at /student/grade/4/ 'function' object has no attribute 'objects' -
Can Django Tenant Schema work with Django Rest Framework?
I am creating a SaaS app with Django and Django Rest Framework. Everything works fine without an API but I have issues with sending a get request to different Tenants. It returns users from all the tenants in the database even if I specify the subdomain. For Example: http://goldlimited.localhost:8000/dashboard/api/users Returns the same information as http://missinglinkgm.localhost:8000/dashboard/api/users The view is a basic ModelViewSet class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.filter() serializer_class = UserSerializer And the Serializer class UserSerializer(ModelSerializer): class Meta: model = User exclude = ("password",) And Route router = routers.DefaultRouter() router.register('user', UserViewSet, 'user') I am wondering if there is a configuration I am missing to make DRF work with Django Tenant Schema. -
Running setup.py install for scikit-learn ... error
I am using MacOs Mojave and currently trying to run the project available on GitHub on this link. I have installed latest version of python(i.e. python 3.8) and currently facing issues while installing the requirements, mainly in scikit-learn. Either way I am getting the same error. Kindly help me through out to run this project completely on my machine locally. I've also raised an issue on the main GitHub page regarding this and still waiting for an adequate response. -
How can i extract data in django template if multiple rows are sent to template containing multiple colums?
sir I am trying to send multiple rows from a database containing multiple columns. Data is sent successfully to the HTML template in Django but when I tried to print particular columns of rows sent, data is not showing up. please help?this is appearing as resultviews.py[template.html][3[]]3 -
How do i redirect a user to a specific page based on their login credentials using Django, HTML?
''' <!DOCTYPE html> <html> <head> <title> XXXTechnologies </title> </head> <body> <form> <input type="button" value="Back" onclick="history.back()"> <p> User Login Form </p> Username: <input id="username" type="text" name="username" > <br> Password: <input id="password" type="password" name="password" > <br><br> <input type="submit" name="Login" value="Login"> </form> </body> </html> from django.db import models class customerlogin(models.Model): user_name = models.CharField(max_length=30) pass_word = models.CharField(max_length=30) ''' I am new to django and stackoverflow so i apologise if my questions isn't informative enough. I'm trying to programme my django to redirect users to custom html pages based on their login credentials. For example, my first user has the credentials - user=user1 pass=password1 . I have created a separate user1.html page for him so when user1 enters his login info and presses login, he is automatically redirected to user1.html. When user2 logs in, he is redirected to user2.html etc. How can i enable this is the most basic and non complicated way. I will just be using this for a small demo session therefore the code security and so on is not important in this case . Any help would be much appreciated ;D