Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass values from foreign key to ajax calls with django model
I have a fairly simple model in Django: class TimeReport(ValidateModelMixin, models.Model): created_at = models.DateTimeField(default=datetime.now) created_by = models.ForeignKey(Person, on_delete=models.DO_NOTHING) year = models.CharField(max_length=9) TERM_CHOICES = [ ('winter', 'winter'), ('summer', 'summer') ] term = models.CharField(max_length=255, choices=TERM_CHOICES) ... class Person(AbstractUser): ... Now, I have a view that generates a template that makes ajax calls once the page is loaded. The ajax call that requests another view: def get_time_reports_api(request, year, term): if request.is_ajax(): qs = TimeReport.objects.filter(year=year, term=term).all() return_value = serializers.serialize('json', qs) else: return_value = 'fail' mimetype = "application/json" return HttpResponse(return_value, mimetype) Obviously, this view returns the foreign key within the created_by field. How can I make sure I pass along the first_name and the last_name of the Person with each TimeReport entry? If I'm not mistaken, I should use annotate but I am struggling with the way it should be put together... -
Django Cors headers added cors-origin-allow-all=True but still gives 403 forbidden error
I am Working on a project where i have installed django cors headers app and done the cors-origin-allow-all=True but it is still giving 403 forbidden error when i am acceing api endpoints from django rest framework.django cors headers issue -
How to create a model that summary from others model, and not save into database but show in admin page?
I have a problem: I need to create a table in admin page that summary data from others model but it's not a actually real model and not be saved into database. How to implement this? -
django template tag in static js files
I want to use template tag and variables in static js files. I'll give you 3 files. no1_ index.html no2_ inc/index.html no3_ index javascript file no1 file is template. html tags in here. and it refers to no2.file to include some scripts. no2.file has some kinds of script includes. and it refers to no3.file to make my own scripts. in no3.file, I want to deal with my template variables from view.py but at no3.file, It can not read template tags and variables. what can I do for this issue? no1_index.html {% load static %} {% load mathfilters %} {% extends 'mobileWeb/base/base.html' %} {% block content %} {% include 'mobileWeb/inc/index/index.html' %} <div id="map" style="width:80%;height:300px; margin:20px auto; border-radius: 10px;"></div> <div style="width:90%; margin:auto"> <!-- this row will wrapping foreach--> {% for mart in marts %} <div class="row"> <div class="col-xs-5" onclick="martClick({{ mart }})"> {% with "/mobileWeb/images/"|add:mart.imageFileNo|add:".png" as path %} <img src="{% static path %}" style="width:120px; height:120px; margin-top:10px;"> <br> <h3>{{ mart.name }}</h3> {% endwith %} </div> <div class="col-xs-7" style="height:200px; overflow:scroll" data-toggle="modal" data-target="#martModal" data-whatever="{{ mart.id }}_{{ mart.name }}"> {% for item in items %} {% if mart.id == item.mart %} <div> <h4 style="color:mediumpurple;">{{ item.name }}</h4> {% if item.discountPrice == 1 or item.discountPrice == 100 %} <h6><span … -
Django REST Framework - Additional field in ModelSerializer
In my ModelSerializer, I want to add required field re_password. I want to use it during creating User model to check if re_password equals password field. class UserSerializer(serializers.ModelSerializer): class Meta: model = User re_password = serializers.CharField(allow_blank=False, write_only=True) fields = ('email','password') def validate_password(self, password): password, re_password = itemgetter('password', 're_password')(self.initial_data) if not password == re_password: raise serializers.ValidationError('Passwords must be the same.') My problem is that when I add re_password to fields I get error: Field name `re_password` is not valid for model `User`. (which is obvious in this case) But if I don't, serializer don't see my additional field. My goal, is to get following error, when there is no re_password field in POST request: "re_password": [ "This field is required." ] I know that I can write code to check it, but maybe there is a way for a serializer to do it? -
How do I connect forms to models in Django?
I've just started learning Django, and I have questions regarding forms and models. So what I'm trying to create, in simplified feature, is a user inputs his/her basic information--phone #, instagram account, facebook account, and so on--then the data is stored in database and show up dynamically to the user. Just like social media. But I'm having confusion with forms and models. What I first did was create forms, like below (forms.py) : from django import forms from django.contrib.auth.models import User class InputUserInfo(forms.Form): phone = forms.CharField(max_length=20) instagram = forms.CharField(max_length=20) facebook = forms.CharField(max_length=20) # and so on. Don't mind about which field to use. then I have my views.py file, written as below: from django.shortcuts import render, redirect from .forms import InputUserInfo def inputuserinfo(response): if response.method == "POST": form = InputUserInfo(response.POST) if form.is_valid: form.save() return redirect('home') else: form = InputUserInfo() return render(response, 'inputuserinfo.html', {'form' : form } then I have my inputuserinfo.html file, like below: {% extends 'base.html' %} {% block content %} <form method="post" action='/inputuserinfo/'> {% csrf_token %} {{form}} <button type='submit'>Done</button> </form> {% endblock%} Now the problem is, I don't know what to do with my models.py. I don't know which code to write in models.py to store the input … -
Writing a Class Based View that Returns a Model instance made by the authenicated_user
I am super new to Python and Django and am trying to get the Model instance made by the current user. I can get the current user.id as the pk but am struggling to find out how to reference that current user and apply that to the View. Currently I have the CustomUser and Profile on a OneToOne Relationship but both are running different pk's ( which makes sense) but while i can get the current users id and apply it through a url its referencing the CustomUser and not the Profile. So i have this View being accessed by a button in a User Inferface that is supposed to call the Profile instance in a DetailView and then a follow on UpdateView class CustomUser(AbstractUser): class Meta: pass def __str__(self): return f"Username: {self.username}, PK: {self.id}" class Profile(models.Model): # TODO: Define fields here # add additional templates under templates/users. Add to the tuples below in this format. USER_TEMPLATES = ( ('users/generic/generic.html', ('generic')), ('users/clothing/clothing.html',('clothing')) ) #model fields author = models.OneToOneField(CustomUser, on_delete=models.CASCADE, editable = False, related_name = 'user') title = models.CharField(verbose_name = 'Company Name', max_length= 50) slug = models.SlugField(editable=False,max_length = settings.SLUG_TITLE_MAX_LENGTH) st_address = models.CharField( max_length=50, verbose_name = 'Street Address') city = models.CharField(blank = … -
Django get_or_create multiple rows without loops
I have an existing Django model which may or may not contain the results from a python calculation. How do I test for and add multiple rows if it does not exist? The docs explain very nicely how to do one entry. Additionally there are various solutions for how to insert multiple rows. I specifically need to (i) add bulk (ii) if it does not already exist. If loops are the only way, then so be it. -
importing top-level Package - python
/folder1 /packageFolder /subfolder /foo.py /folder2 /bar.py Hello I'm trying to import bar.py into foo.py but I'm getting this error: ValueError: attempted relative import beyond top-level package why? and how can I solve this? -
Assigning a rank to the scores from the database in django and displaying it on the html page
I'm creating a quiz app, i am done till displaying scores, but i'm stuck at ranking the students based on their scores which has directly been stored in the database, so how do i get scores from the database and rank the students according to their scores and display it on my html page, I'm using django for this, requesting model, views, and html code. -
Display User's Django Rest Framework Auth token in templates
I recently implemented Django Rest Framework into my project, and I was wondering if it is possible for me to display the Token that has the associated User object attached to it. So if I, for example could do this in the templates: {{ user.token }}. -
FormView: form is absent in the context
Django 3.0.4 template {% debug %} <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Copy"> </form> forms.py from django import forms from yandex_ads.models import YandexTextAdTemplates def get_choices(): return [(item.id, str(item)) for item in YandexTextAdTemplates.objects.all()] class CopyForm(forms.Form): forms.ChoiceField(choices=get_choices()) views.py from django.views.generic.edit import FormView class CopyAdTemplate(FormView): template_name = 'yandex_ads/copy_form.html' form_class = CopyForm success_url = reverse_lazy("home") **The problem: ** form param is not transmitted to the context. It is absent. But in the screenshot (with a black background) it is visible that FormMixin handled the form. Well, it disappeared somewhere. Could you help me solve or at least localize the problem? -
Zappa async task not being async
I'm adding a function to send emails from my zappa serverless application The sending mail process can run over the 30 seconds limit of AWS Api Gateway, giving the user a 504 response. So, following the approach on Zappa documentation, I have tried to set an asynchronous execution The code seems to be very simple from zappa.asynchronous import task from django.core.mail import send_mail as django_send_mail @task def send_mail(subject, body, from_email, to_emails): django_send_mail( subject, body, from_email, to_emails, fail_silently=False, ) Then in my function I just call the async function: send_mail( 'My Subject', 'My email body', 'noreply@mydomain.com', [user.email], ) Still, get a 504 I have tried setting it as sns, added to zappa_settings.json then "async_source": "sns", And then on the code: from zappa.asynchronous import task_sns @task_sns def send_mail(subject, body, from_email, to_emails): django_send_mail( subject, body, from_email, to_emails, fail_silently=False, ) Same error Last, I have tried invoking it directly with from django.core.mail import send_mail as django_send_mail enter code herefrom zappa.asynchronous import run def send_mail(subject, body, from_email, to_emails): run( django_send_mail, (subject, body, from_email, to_emails), {'fail_silently': False}, service='sns', ) I also tried removing the service parameter It seems that for some reason, Zappa doesn't understand that this is a lambda environment and run it synchronous? -
concat two {{}} interpoled values
have a valuesthat is sent hidden in a form like this <input class="form-control {% if form.title.errors %}is-invalid{% endif %}" name="name" size="16" type="hidden" value="{{post.user.name}}" > now want to contact two values in the value field value field value="{{post.user.name}}" > and value="{{post.user.lastname}}" > already tried tried with |concat and also tried to merge the strings with + but it didn´t work how i can concat those two string and add a space in the middle ? -
Python django Foreign Key Relationships problem
I am working on an online school project, where I got classes, and in the classes I have different subjects, I added a one-to-many(ForeignKey) Relation between "Classes" and "Subjects", but when it comes the view theme on the HTML page Subjects from 2.Class comes to show on 1.Class one page(all Subjects are showed in one class) How to Fix this problem?? (How to keep 2.Class Subjects in the 2.Class page as well for 1.Class?) MY CODE viws.py def classes(request): classes = Class.objects context={ 'class':classes } return render(request, "templates/Classes.html", context) def subjects(request, sub_id): classes=get_object_or_404(Class, pk=sub_id) subject=Subject.objects.all() context={ 'classes':classes, 'subject':subject } return render(request, "templates/Subjects.html", context) Models.py class Class(models.Model): title=models.CharField(max_length=200) image=models.ImageField(upload_to="images") class Subject(models.Model): title=models.CharField(max_length=2000) Class=models.ForeignKey(Class, on_delete=models.CASCADE) Webpage {%for subject in subject.all%} <div class="cardrow"> <div class="cardcolumn"> <a href="#"> <div class="card"> <h1>{{subject.title}}</h1> </div> </a> </div> </div> {%endfor%} So again all subjects are showing in one class. tho I added a Foreign Key relationship Thanks -
Work with a Django model (table) with an external python script
I am working with django and I have created some models (tables). Working directly on my django project all is ok, I can visualize and modify data with no problems. But when I want to work directly with a Python script out of my Django project, it can't access to the tables, because it says the table doesn't exist. Below I show from the PostgreSQL dashboard one of my tables. How I have to do it, to work with it, in a independent python script? I have done something like this, import psycopg2 # Trabajar con PostgreSQL def bbdd_connect(): con = psycopg2.connect( host = '127.0.0.1', database = 'lorawan_platform_app', user = 'XXX', password = 'XXX', port = 5432 ) # Cursor cur = con.cursor() return con, cur def bbdd_desconnect(con, cur): cur.close() con.close() def add_new_data(): # Establecer conexión con BBDD y generar cursor con, cur = bbdd_connect() # Query - Obtenemos el id mayor junto con su fecha. query = "SELECT data_id, data_timestamp FROM Platform_App_dataerror WHERE data_id = (SELECT MAX(data_id) FROM Platform_App_dataerror);" cur.execute(query) cosa = cur.fetchall() # MIRAR LO DEL DUPLICADO if len(cosa) == 0: params = {'from':'2020-01-01 00:00'} else: params = {'uplink_id_start':cosa[0][0]} # Finalizamos la conexión con la bbdd bbdd_desconnect(con, cur) … -
Any drawbacks to a foreign key pointing to a person, not a user account?
I have a Django application that uses two simple database tables to represent users (I've simplified these a little for brevity): class Person: first_name = models.CharField() last_name = models.CharField() email = models.CharField() class User: person = models.OneToOneField('Person') last_login = models.DateTimeField(blank=True, null=True) roles = models.ManyToManyField('Role', blank=True) I pre-populate the Person table with entries from my corporate Active Directory instance, so that I can quickly reference people in our organization. User model instances are created on an as-needed basis (not every person will necessarily have a User account). This application also has various resources that need an owner (via an "owner" column in the respective tables). For example: class SomeResource: owner = models.ForeignKey('User') # ... [other fields here] ... As you can see in the example, the owner column points at the User model. I would like for the users of my application to be able to assign these resources to the necessary individual, and there is a very-real possibility that that Person's User account has not yet been created. I'm wondering: are there any general drawbacks to pointing ownership columns to the Person model instead? I realize that a few alternatives exist: Create User accounts for all Person records, whether they … -
Django create POST intermediate model
I'm using DRM v3.9.4 and have the following models: class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... users = models.ManyToManyField("User", related_name="books", through="BookUser") class BookUser(models.Model): id = models.UUIDField(primary_key=True, editable=False) user = models.ForeignKey("User", on_delete=models.CASCADE) book = models.ForeignKey("Book", on_delete=models.CASCADE) permission = models.CharField(...) class User(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... with the following serializers: class UserSerializer(ModelSerializer): class Meta: model = User fields = ( "id", ... ) class BookUserSerializer(ModelSerializer): class Meta: model = BookUser fields = ('user', 'permission') class BookSerializer(ModelSerializer): users = BookUserSerializer(source='bookuser_set', many=True) class Meta: model = Book fields = ( "id", "users", ... ) extra_kwargs = { "users": {"allow_empty": True}, } When reading (GET) a Book everything is fine: { id: ..., users: [ { user: 'some-uuid', permission: 'read-only' }, ... ] } but when trying to POST using the same payload: { id: ..., users: [ { user: 'some-uuid', permission: 'read-only' }, ... ] } I get an error: KeyError: 'users' looking at the api-guide (https://www.django-rest-framework.org/api-guide/relations/) seems that by default nested serializers are read-only, but I can't make it work. BTW, IMPORTANT: all the users are (and should) already exist, so I expect this POST call to add a record in the intermediate BookUser table, and ofcourse the Book itself, … -
Data not inserting in Django Database using Form DTL
Here is my model.py file class TestData(models.Model): test_date = models.DateField(blank=True) test_name = models.CharField(max_length=255) result = models.IntegerField() And here is my forms.py file class TestDataForm(forms.ModelForm): class Meta: model = TestData fields = ['test_date','test_name','result'] And here is my views.py file def photo_single(request): if request.POST: form = TestDataForm(request.POST) if form.is_valid(): if form.save(): return redirect('/', messages.success(request, 'Order was successfully created.', 'alert-success')) else: return redirect('/', messages.error(request, 'Data is not saved', 'alert-danger')) else: return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger')) else: form = TestDataForm() return render(request, 'photo_single.html', {'form':form}) and here is my photo_single.html file <form>{% csrf_token %} <div class="form-row"> <div class="form-group col-md-6"> <label for="date">Date</label> {{ form.test_date | add_class:'form-control' | attr:'type:date' }} </div> <div class="form-group col-md-6"> <label for="test_name">Test Name</label> {{ form.test_name | add_class:'form-control' }} </div> <div class="form-group col-md-6"> <label for="result">Result</label> {{ form.result | add_class:'form-control' }} </div> </div> <button type="submit" class="btn btn-primary" name="data">Submit</button> </form> When I'm submitting value from form to databasw, I'm getting this in url http://127.0.0.1:8000/photo/?test_date=2020-03-13&test_name=SUGAR&result=23&data= and data is not saving in database. Can anyone help me out why ? I'm messed in this. Am I missed something here ? Thanks -
django upload a file from other python script
I want to save file from the client to the django project server's database from a script. I've tried to do this using a model and a view in the django project, and post request in the other python script, but it keeps return 403 error and not save the file and the data to the database. models.py: class ScreenRecord(models.Model): record = models.FileField(default='output.avi', upload_to='records') writeTime = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) views.py: def getscreenrecords(request): user = User.objects.filter(username=request.POST.get('user')).first() k = ScreenRecord(record=request.FILES.get('record'), user=user) k.save() return HttpResponse('success ' + request.GET.__getitem__('user')) python script to send the file: url = 'http://127.0.0.1:8000/send/screenrecords/' files = {'record': open('output.avi','rb')} values = {'user': 'newUser'} r = requests.post(url, files=files, data=values) print(r) what's wrong in my code or is there a way to do this better? -
Django + React : How to connect them for deployment?
I am running an app with Django+DRF, CELERY+REDIS ,ReactJs+REDUX & JWT, and i am having a hard time connecting backend with the frontend for deployment. i have used create-react-app to generate React code; and npm run build to generate the production build. i have been looking around but i can't find a tutorial on how to link them together. if you guys have any link in your pocket that i can follow i'll be thankful to you. -
Import category CSV data django model with child category
class Category(models.Model): parent_category = models.ForeignKey('self',related_name='child_category_list',on_delete=models.SET_NULL,blank=True,null=True) name = models.CharField(max_length=255) cat_id = models.CharField(max_length=255,null=True,blank=True) path = models.TextField(null=True,blank=True) I have category model and numerous category names and ids in csv.Is there any way to import csv data with parent category? Structure is like: -Computers, Tablets & Network Hardware --Computer Parts ---motherboard --laptops ---hp ---dell -
How to extend the reach of the select_related function of Django Queryset so it includes the table related to a table related to the original table
This is what my models.py looks like class Branches(models.Model): def __str__(self): return self.location location = models.CharField(max_length=256, unique=True) class Daily_Infos(models.Model): class Meta: unique_together = ["date", "branch_id"] def __str__(self): return str(self.date) + " " + str(self.branch_id) branch_id = models.ForeignKey(Branches, related_name='daily_info', on_delete=models.CASCADE) date = models.DateField() class Branch_Prices(models.Model): def __str__(self): return str(self.branch_id) + " " + str(self.menu_item_id) + " " + str(self.price) branch_id = models.ForeignKey(Branches, related_name='prices', on_delete=models.CASCADE) menu_item_id = models.ForeignKey(Menu_Items, related_name='prices', on_delete=models.CASCADE) price = models.FloatField() class Sold_Menu_Items(models.Model): def __str__(self): return str(self.branch_price_id) + " " + str(self.daily_info_id) + " " + str(self.quantity) daily_info_id = models.ForeignKey(Daily_Infos, related_name='sold_menu_items', on_delete=models.CASCADE) branch_price_id = models.ForeignKey(Branch_Prices, related_name='sold_menu_items', on_delete=models.CASCADE) quantity = models.IntegerField() class Menu_Items(models.Model): def __str__(self): return str(self.name) + " " + str(self.size) name = models.CharField(max_length=256) size = models.CharField(max_length=64) start_date = models.DateField() is_active = models.BooleanField() In my views.py, I have this function: def view_sold_items_all(request): sold_menu_items = Sold_Menu_Items.objects.select_related('branch_price_id','daily_info_id') refined_sold_menu_items = [] for smi in raw_sold_menu_items: menu_item = [] menu_item.append(smi.daily_info_id.date) menu_item.append(smi.quantity) menu_item.append(smi.branch_price_id.branch_id.location) menu_item.append(smi.branch_price_id.menu_item_id.name) menu_item.append(smi.branch_price_id.menu_item_id.size) refined_sold_menu_items.append(menu_item) return render(request, 'view_all.html', { 'sold_items':refined_sold_menu_items }) Based on my understanding, the code below (which is in my views.py file) will allow Django to query my database only once. sold_menu_items = Sold_Menu_Items.objects.select_related('branch_price_id','daily_info_id') During the for loop, it will not keep querying the database for the two lines: menu_item.append(smi.daily_info_id.date) menu_item.append(smi.quantity) However, … -
Django ORM filter records between last month 15th date to current month 15th date
I want to filter the queryset records from the previous month's 15th date to the current month 15th. Does someone have any idea how to do it? Models.py class Book(models.Model): name = models.CharField(max_length=100, null=True) author = models.CharField(max_length=100, null=True) created_on = models.DateTimeField(auto_now_add=True) Views.py class BookView(View): def get(self, *args, **kwags): start_date = '15th_of_previous_month' end_date = '15th_of_current_month' qs = Book.objects.filter(created_on__gte=start_date,created_on__lt=end_date) ... -
Django how go get all products for the logged in user only?
i have the following code, and when the page is displayed the table shows all products for all users no matter which user is logged in. I want to show in the table only the products that was created by the logged in user only, not from all users. Any help with my issue ? Thank you in advance. views.py @login_required def eadmin(request): transactions = Product.objects return render(request, 'accounts/index.html', {'transactions': transactions}) models.py class Product(models.Model): details = models.CharField(max_length=1000) opname = models.CharField(max_length=100) pub_date = models.DateTimeField() amount = models.IntegerField() contactemail = models.TextField() purpose = models.TextField() poster = models.ForeignKey(User, on_delete=models.CASCADE) transactionid = models.CharField(max_length=6) def __str__(self): return self.transactionid In the html template: <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">XXXXX</th> <th scope="col">Amount €</th> <th scope="col">Transaction ID</th> </tr> </thead> {% for transaction in transactions.all %} <tbody> <tr> <th scope="row">-</th> <td>{{ transaction.opname }}</td> <td>{{ transaction.amount }}</td> <td>{{ transaction.transactionid }}</td> </tr> </tbody> {% endfor %} </table>