Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to Upload database file using python requests and sending to django API
Hi I have a database file. I want to send this database file via python requests post method to my django server and store this database file somewhere in my server. I have following code to send the database file: database = {'uploaded_file': open('<my_local_path>/Old_DB.sqlite3', 'rb')} response = requests.post('http:192.168.20.4/api/app/receive-database', data=database) print(response.status_code) On my API: class DatabaseReceive(views.APIView): permission_classes = (permissions.AllowAny,) def post(self, request): database = request.data data = database.get('uploaded_file') try: newDB = open('<path_to_store_the_database>/New_DB.sqlite3', 'wb') newDB.write(data) result = "Sucess" except Exception as e: result = e return Response(status=status.HTTP_200_OK, data=result) So, basically I am sending the database as a binary file to my api. On my api, I am creating another binary file and trying to write the binary contents from database to my to this new binary file making it a new database. Here I can see that 'data' is a binary contents, but I'm not being able to write this 'data' to my newDB binary file. -
How add user to a group when update and create a user
I created a bunch of groups fallowing this link: https://stackoverflow.com/questions/22250352/programmatically-create-a-django-group-with-permissions#:~:text I subscribed the User class adding a choice field called "role". Basically, that means what role that user has. That way if a user has the role of "staff" . Thus It'll have permissions of the group staff. The problem is: I can't get django to respond the way I expected. I put a signal after saving that it should add the user to the group according to their role. The program looks like this: # project/app/model.py class User(AbstractUser): class Roles(models.IntegerChoices): SUPER = 0, _('SuperAdmins') COMPANY = 1, _('Company') UNITY = 2, _('Unity') STAFF = 3, _('Staff') role: Roles = models.IntegerField(choices=Roles.choices, default=Roles.STAFF, verbose_name=_("Role")) My signal is like: GROUPS = ['SuperAdmins', 'Company', 'Unity', 'Staff'] @receiver(post_save, sender=User) def user(sender: User, instance: User, created: bool, **kwargs) -> None: """ This receiver function will set every staff pages that is created to the group staff. :param sender: the model that will trigger this receiver :param instance: the instance :param created: if it was already created :param kwargs: :return: None """ if created: group = Group.objects.get(name=GROUPS[instance.role]) instance.groups.add(group) else: group = Group.objects.get(name=GROUPS[instance.role]) instance.groups.add(group) print("update") When I go to the admin page and I create a new … -
Django MySQL Access denied for user 'user_name'@'localhost' to database 'db_name'
I'm brand new to Django (1st day) and setting up and environment on a MAC. I'm inside the environment created by pipenv and trying to execute python3 manage.py migrate. I get the error "Access denied for user 'user_name'@'localhost' to database 'db_name'". I have no problems connecting to the database either inside or outside the pipenv environment using the mysql command line tool. MAC version 12.3.1 MySQL version = 8.0.28 Python version = 3.9.12 Ideas? TIA... -
How Do You Properly Copy ManyToMany Fields From One Model To Another
I am trying to override the SAVE of one model and copy specific fields to another model. I swear I had this working....but now it's not. Anyway...Here's an example of what I thought used to work.... def save(self, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) NewModel = Target.objects.create( field=self.field ) NewModel.m2mfield.add(*self.m2mfield.all()) I swear this use to work but now when it gets executed...the "normal" fields copy as expected but the M2M is blank. I've confirmed that the model shows the values in the M2M field....but for whatever reason they aren't being copied over to the "Target" model. Thanks in advance for any thoughts on what I might be doing wrong or what may have chnanged. -
Django multiple distinct values queryset for SQLDB
I'm trying to get a list of results that have distinct x and y values, but I also want to return color along with them. Since I'm using an SQLDB I'm not allowed to use the fieldnames arg of distinct. Is there a good work around for this? All the examples I'm been looking up haven't been working out. The query that I'm not allowed to run: queryset = Tile.objects.values('x', 'y', 'color').distinct('x', 'y') -
Search functionality in list view
I am trying to implement search functionality in my CBV list view. To do that have I written a "get_queryset". The view looks like this class List(ListView): model = Client ... def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) query = self.request.GET.get('q') if query: return qs.get(user=query) return qs When I have it like this, I get the following error: "Field 'id' expected a number but got 'x'.". x is in this case whatever I inputed in the search field. But if I change user to something invalid, I get the following error: "Cannot resolve keyword '' into field. Choices are: user, user_id". I don't understand why user does not work in this case and why it uses the field "id" if I specify user. -
Django - file isn't being downloaded
I have a django app, with a vuejs frontend. I'm making a PUT request from my Vue front-end. As a response, I want a xlsx file to be generated & downloaded. For some reason, the file isn't being downloaded. Here's the generate & download function. def export_to_main(request): if request.method == 'PUT': response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'inline; filename="exported_to_main.xls"' selected_claims = Claim.objects.filter(status='PA') workbook = Workbook(encoding='utf-8') group_header_style = easyxf( "font: bold true; pattern: back-colour blue;") number_style = easyxf(num_format_str="#,##0.00") date_style = easyxf(num_format_str='DD-MM-YYYY') sheet = FitSheetWrapper(workbook.add_sheet("Sheet 1")) header_column = count() sheet.write(0, header_column.next(), 'Book Number', group_header_style) sheet.write(0, header_column.next(), 'Dossier', group_header_style) sheet.write(0, header_column.next(), 'Dossier Type', group_header_style) for i, claim in enumerate(selected_claims, 1): try: column = count() sheet.write(i, column.next(), claim.book_nr) sheet.write(i, column.next(), claim.kind) sheet.write(i, column.next(), getattr(claim.letter_claim_type, 'label')) except IndexError: print("error"*5) pass # selected_claims.update(status='AP', exported_to_main=datetime.datetime.now()) workbook.save(response) return response If I print(response) I get the workbook in my console. So the excel is generated properly. For some reason, it is not being downloaded on the frontend though. Here's the vue code: <v-row> <v-btn color="success" @click="exportMain" download > Export to main </v-btn> <v-spacer></v-spacer> <v-btn color="success" :href="xls"> Export Excel </v-btn> </v-row> and this method is being called on that button click: export_to_main({commit}) { const url = action="{% url 'control:export-to-main' %}" commit('set_loading', … -
API view returning { "detail": "Not found." },
class User(models.Model): user_id = models.CharField(max_length=255, unique=True) mobile = models.CharField(max_length=12) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) profile_image = models.URLField(null=True) email = models.EmailField(null=True) posts = models.ManyToManyField('uploads.Posts', related_name='post_user') created_on = models.DateTimeField(default=timezone.localtime) updated_on = models.DateTimeField(default=timezone.localtime) is_deleted = models.BooleanField(default=False) class Posts(models.Model): url = models.URLField(null=True) description = models.TextField() created_on = models.DateTimeField(default=timezone.localtime) updated_on = models.DateTimeField(default=timezone.localtime) is_deleted = models.BooleanField(default=False) These are my models, I have created a serializer for Posts and nested it under a UserPostSerializer. class PostSerializer(serializers.ModelSerializer): class Meta: model = Posts exclude = ('id', 'created_on', 'updated_on', 'is_deleted') class UserPostsSerializer(serializers.ModelSerializer): posts = PostSerializer(many=True) class Meta: model = User fields = ('user_id', 'profile_image', 'posts',) However, when I create a view like this- class UserPostsView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserPostsSerializer def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) response = Response(serializer.data) return response my API returns { "detail": "Not found." } Ideally, the view should list all the users along with their posts. Something like: { "user_id": "abcd", "url": "http:....com", "description": "Lorem ipsum" } -
FIle path is correct but still getting filenotfound error [Django]
I have written a small django project. Inside the project I am calling a different script to run. Example code below: cmd1 = 'python3 myscript.py' subprocess.Popen(cmd1) This works fine on my windows machine but when I run the same project on my linux machine, it shows error that No such file or directory exists I am not able to understand the cause of this error. Please help me fix this [The project was first built on windows that as it is copied from windows machine to linux machine] -
Custom field with special constrains in DRF serializer
I'm trying to add a custom field with some special constrains in DRF serializer. Following are 2 sample models: class ModelA(models.Model): field1 = models.CharField(max_length=200) field2 = models.CharField(max_length=200) field3 = models.CharField(max_length=200) class ModelB(models.Model): field4 = models.ForeignKey(ModelA, on_delete=models.CASCADE) field5 = models.CharField(max_length=200) What I want is a serializer based on ModelA, but with a custom field displaying a string combining field5s of all ModelB instances this ModelA instance has. I know this API design is a little bit weird, but based on the existing code base, we have to do it this way. Also I wanna this field to be writable, so SerializerMethodField doesn't work. I tried to follow the example here: https://www.django-rest-framework.org/api-guide/fields/#examples. But my case is a little bit different, since it involves multiple models. Some sample code would be very helpful! Thx! -
django websocket cannot send data to client after receiving it
class WSTestView(WebsocketConsumer): def connect(self): self.accept(); self.send(json.dumps({'status': 'sent'})) # client receives this def receive(self, text_data=None, bytes_data=None): notifications = Notification.objects.filter(receiver=text_data) # receives user id serializer = NotificationSerializer(notifications, many=True).data self.send(serializer) # client does not receives this Frontend // ... useEffect(() => { socket.onmessage = (e) => { console.log(e.data) } }, []) // ... I've just started with django-channels and am working on a consumer that sends the user's notifications when it receives the user's id but on the frontend the onmessage event does not receive anything, how can I fix this and is there a better way that I can implement this? -
Interogation and creation of sqlite table using django
I have some tables in my database and I want to combine somehow. The tables are about heartrate (data, hour:minutes, heartrate for that minute), other table sleep (start sleep, end sleep, etc.). I want to combine them and to know what is the heartrate in that interval of sleeping and after that to put the tag "sleeping" for that day, hour, heartrate. I don't know now if it make sense to create another table (date, hour, heartrate, tag) or to put that tag in the first table with heartrate. I want to mention that the values that I have in the tables are imported via django, so it will be added more values for different user there. The interrogation in the first table with the interval of sleeping from table 2, id did it with command join? Do you have some example of code in django for this? -
Redirect user from login to crud first page
I'm new in django and even in python I have a project 'mysite' with 3 apps. Configs of urls mysite urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), # user management path('account/', include('allauth.urls')), #local path("", include("pages.urls", namespace="pages")), path("imoveis/", include("imoveis.urls", namespace="imoveis")), ] App Users - no urls.py App Imoveis - urls.py: from django.urls import path from . import views app_name = "imoveis" urlpatterns = [ path('', views.form, name='form'), path('create/', views.create, name='create'), path('view/<int:pk>/', views.view, name='view'), path('edit/<int:pk>/', views.edit, name='edit'), path('update/<int:pk>/', views.update, name='update'), path('delete/<int:pk>/', views.delete, name='delete'), ] and App pages - urls.py: from django.urls import path from . import views app_name = "pages" urlpatterns = [ path("", views.HomePageView.as_view(), name="home"), ] I have a template folder (a folder not inside any app or project) with: Accounts Folder: login.html, logout.html and signup.html -Imoveis Folder: form.html, read.html and view.html and base.html and home.html direct in template folder I want to when user log in they goes to form.html. I don't know how to change from base.html I put in form.html : {% extends 'account_login.html' %} but nothing. Any help are welcome. Regards -
Django server doesn't serve requests
I've got a django server up and running. When I try to it any api in it, it gives error "Error: Parse Error: Expected HTTP/" on postman. I've tried to access a single api directly from browser by typing "localhost:9001/". I have a default health check api which should ideally run on this, but none of my apis are working on this. -
Django javascript online connection with socket?
Learning Django/socket, I challenged myself with a little online 1v1 memory card game. For the moment the code is able to create a landing page then creating/joining a room. The room present the memory card game with a chat. My following problem is that the memory card is not the same for the room, look like a random is generate 2 times even if player are in the same room If you have any clue, adivices I will appreciate. (not a pro or a student, just doing it for my pure enjoyement, sorry if the following code contains errors) Here is my code HTML : % extends 'base.html' %} {% load static %} {% block content %} <div class="container main"> <div class="sideme"> <div class=" w-100 d-flex justify-content-center"> <div> <strong class="my-3 text-white text-center"> <p class ="mt-3"id="userdiv"> </p> <span class="my-3">Total User : <span id="user_num"></span></span><br> <div class="d-flex justify-content-between"> <div><span id="userTurn"></span> Turn</div> <div id="lastStepDiv"> </div> </div> </strong> <div class="wrapper"> <ul class="cards"> <li class="card"> <div class="view front-view"> <img src="{% static 'images/que_icon.svg' %}" alt="icon"> </div> <div class="view back-view"> <img src="{% static 'images/img-1.png' %}" alt="card-img"> </div> </li> <li class="card"> <div class="view front-view"> <img src="{% static 'images/que_icon.svg' %}" alt="icon"> </div> <div class="view back-view"> <img src="{% static 'images/img-6.png' %}" … -
Django dynamic sitemap without using models
So, basically I have data coming from an API. There's no model and the data is not stored in my database. I just send request and get data. The problem is every single tutorial for dynamic sitemaps in Django requires usage of Models. Also came across this question but it doesn't have a proper solution. Is it possible to use Django's built-in sitemap module in this scenario or should I create my own script that generates sitemap programmatically? -
How to create url path dynamically from list of dicts
I have a list of dicts that contains a path, view, and view name suppose I have the following list with many of URLs, that are in the following format url_lsts = [ {"path" "preview/", "view": reverse("app:index"), name="preview"} ... ] urlpatterns = [ path(url["path"], url["view"], name=url["name"]) for url in url_lsts ] when using reverse i'm getting following url django.core.exceptions.ImproperlyConfigured: The included URLconf 'aisp.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I've tried reverse_lazyand got the following URL raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). -
How to display a line chart with Charts.js and Django?
I would like to display a line chart in my Django template with chart.js but I'm unable to display something, except variables labels and data. The data structure seems to be correct according to the documentation, what could cause the issue ? > labels ['Home'] > data [{'x': '2022-01-07 16:00:00', 'y': 1.0}, {'x': '2022-01-08 16:00:00', 'y': 1.01}, {'x': '2022-01-08 17:00:00', 'y': 1.05}] base.html <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"> </script> template.html {% extends "base_generic.html" %} {% load static %} {% block content %} {% block scripts %} <script> // jquery function $(document).ready(function(){ var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: {{labels}}, datasets: [{ label: 'Home data', data: {{data}} }] } }); }); </script> {% endblock scripts %} <canvas id="myChart" width="400" height="100"></canvas> {% endblock %} -
how to change form field from dropdown list to radio button in django if the options in dropdown are being inherited from another model?
i am working on an application where i can select item from drop-down list and buy them. i have a form field which is a drop-down list(items are connected to other model via foreign key.i want to make those options appear as radio buttons instead of drop down list my models.py class Plans(models.Model): plan_name = models.CharField(max_length=50) speed = models.IntegerField() price = models.FloatField() def __str__(self): return self.plan_name def get_deadline(): return dt.today() + timedelta(days=30) class Orders(models.Model): user = models.ForeignKey(CustomUser, primary_key=True, on_delete = models.CASCADE) pack = models.ForeignKey(Plans, on_delete = models.CASCADE) start_date = models.DateField(auto_now_add=True) end_date = models.DateField(default=get_deadline()) is_active = models.BooleanField(default=True) def __str__(self): name = str(self.user.username) return name def get_absolute_url(self): return reverse('home-home') my forms.py(i tried using the init method but my drop down list vanishes when i use it) class BuyPlanForm(forms.ModelForm): error_css_class = 'error-field' required_css_class = 'required-field' class Meta(): model = Orders fields = ['pack'] #def __init__(self, *args, **kwargs): # super(BuyPlanForm, self).__init__(*args, **kwargs) # for field in self.fields.values(): # if isinstance(field.widget, forms.Select): # field.widget = forms.RadioSelect() my views.py class UserBuyPlan(LoginRequiredMixin, CreateView): template_name = 'plans/plan.html' form_class = BuyPlanForm def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) please help.(sorry i tried my best to explain the problem i am having but my english isn't that great) -
Django many-to-many relations
I'm trying to create a web app in which users can participate in some groups (every user can be part of multiple groups), and I want to be able to make both queries like group.users_set() and user.groups_set() I want to see all groups a user is participating to in the admin page of every user and vice versa. My last attempt was this: class CustomUser(AbstractUser): groups = models.ManyToManyField('Group', through='Participation') class Group(models.Model): group_name = models.CharField(max_length=200) group_password = models.CharField(max_length=200) customusers = models.ManyToManyField('CustomUser', through='Participation') class Participation: customuser = models.ForeignKey(CustomUser, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) but I get django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'userreg.admin.CustomUserAdmin'>: (admin.E013) The value of 'fieldsets[2][1]["fields"]' cannot include the ManyToManyField 'groups', because that field manually specifies a relationship model. Before, with just users = models.ManyToManyField(CustomUser) in the Group class and without the Participation class, I was able to get half of my goal, seeing the list of logged users in the admin page. What am I doing wrong? -
I can't render through the foreign key
I have a doubt. I want to show a name(nombre) of each client (cliente) with the total amount of money owed, so that each record is in a different cell. In pycharm I have this written: presupuestos.html <tbody> {% for pago in pagos %} <tr> <td> {% for presupuesto in presupuestos %} {{presupuesto.cliente.nombre}} {% endfor %} </td> <td> {{pago.cantidad_pagada}} </td> </tr> {% endfor%} </tbody> What happens is that when rendering this: {% for presupuesto in presupuestos %} {{presupuesto.cliente.nombre}} {% endfor %} The name appears, which is what I want to show, the bad thing is that all the repeated names appear in the same cell. But when using this: {{pago.estimate.cliente.nombre}} Nothing appears and If I put {{pago.estimate}} 'none' appears, but if there was nothing in the next loop the names would not appear I do not understand if my problem is due to my view.py or my models, possibly it is due to "estimates" in my payment model but I do not understand how to change it to be able to access that value pagos/models.py class Pagos(models.Model): numero_transaccion=models.IntegerField() estimate=models.ForeignKey(Presupuestos, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.numero_transaccion}' presupuestos/models.py class Presupuestos(models.Model): cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.cliente}' clientes/models.py class Clientes(models.Model): nombre … -
How can I include reverse related items in s Django serializer?
I'm trying to add all Payments that relate to a PayrollRun in the serializer to also return this. But how would I basically add reverse relations to a serializer? # views.py class PayrollRun(APIView): """ Retrieve payroll runs including line items for a company """ def get(self, request): # Get the related company according to the logged in user company = Company.objects.get(userprofile__user=request.user) payroll_runs = Payroll.objects.filter(company=company) serializer = PayrollSerializer(payroll_runs, many=True) return Response(serializer.data) # models.py class Payroll(models.Model): """ A table to store monthly payroll run information of companies """ # Relates to one company company = models.ForeignKey(Company, on_delete=models.CASCADE) month = models.DateField() amount = models.DecimalField(decimal_places=2, max_digits=10) line_items = models.PositiveIntegerField() def __str__(self): return f'Payroll run month {self.month} for company {self.company.name}' class Payment(models.Model): """ A table to store all payments derived from an offer """ # Relations offer = models.ForeignKey(Offer, on_delete=models.CASCADE) month = models.ForeignKey(Period, on_delete=models.CASCADE) payroll_run = models.ForeignKey(Payroll, on_delete=models.CASCADE, null=True, blank=True) # is populated once the payroll run was created amount = models.DecimalField(decimal_places=2, max_digits=10) def __str__(self): return f'{self.offer} with an amount of {self.amount} and payment month {self.month}' # serializers.py class PayrollSerializer(serializers.ModelSerializer): class Meta: model = Payroll depth = 1 fields = '__all__' right now returns the following without the related payment instances [ { "id": 12, … -
Put a book in several categories (Django)
I have a model named "book" and a model named "BookCategoty". how i can assign infinite category ForgienKeys? for books that fall into several categories. -
Django Rest Framework - Wrapping the JSON response with the name of the model
My goal is to customize the JSON response from Django DRF when listing items. The model: class Object(models.Model): code = models.CharField(max_length=16, primary_key=True, unique=True) item = models.CharField(max_digits=128) last_updated = models.DateTimeField(auto_now=True, editable=False) the serializer: class ObjectSerializer(serializers.ModelSerializer): class Meta: model = Object fields = ['code', 'item'] the view: class ObjectList(generics.ListAPIView): queryset = Object.objects.all() serializer_class = ObjectSerializer def list(self, request): queryset = self.get_queryset() serializer = ObjectSerializer(queryset, many=True) return Response(serializer.data) with this setup the JSON response is: [ { "code": "111", "item": "aaa" }, { "code": "222", "item": "bbb" } ] Is there a way to wrap the response with the name of the model? Expected result would be: "objects": [ { "code": "111", "item": "aaa" }, { "code": "222", "item": "bbb" } ] -
Save django Models in different script and run that script with HTML button
I have model.py as ''' class Fruit(models.Model): name = models.CharField(max_length=16) weight = models.IntegerField(max_length=16) color = models.CharField(max_length=16) class Veg(models.Model): name = models.CharField(max_length=16) weight = models.IntegerField(max_length=16) ''' I have myFunction.py as ''' def makeModels(file): with open(file, 'r') as f: line=f.readline() while line: if line.split(',')[0] == 'fruit': a = Fruit(name=line.split(',')[1], weight=line.split(',')[2], color=line.split(',')[3]) a.save() if line.split(',')[0] == 'veg': b = Veg(name = line.split(',')[1], weight = line.split(',')[2] b.save() line = f.readline() ''' and files as abc.txt "fruit,apple,3,red\n fruit,banana,1,green\n veg,spinach,4\n veg,collard,2\n fruit,banana,3,yelow\n veg,broccoli,3\n fruit,orange,1,orange" I want to create an HTML button to trigger this function/script and also create a celery scheduler to schedule a trigger to run at a time on a daily basis. This is on a django framework. Please help me on how to approach it. The running external function to save models through html button and scheduling it part. Thank you!