Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can we add data into database using migration files in django?
I am currently using Django 3.2 i wanted to add data to Database using migration files. from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sbimage', '0001_initial'), ] operations = [ migrations.CreateModel( name='AuthNumberR', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('auth_number_r', models.CharField(max_length=64)), ], ), migrations.RunSQL("INSERT INTO AuthNumberR (id, auth_number_r) VALUES (2, 'c');"), ] is this the proper way to insert data? -
Is there a proper design pattern for this situation?
I'm building a simple crud app in Django which is basically enhanced reporting for commerce related software. So I pull information on behalf of a user from another software's API, do a bunch of aggregation/calculations on the data, and then display a report to the user. I'm having a hard time figuring out how to make this all happen quickly. While I'm certain there are optimizations that can be made in my Python code, I'd like to find some way to be able to make multiple calculations on reasonably large sets of objects without making the user wait like 10 seconds. The problem is that the data can change in a given moment. If the user makes changes to their data in the other software, there is no way for me to know that without hitting the API again for that info. So I don't see a way that I can cache information or pre-fetch it without making a ridiculous number of requests to the API. In a perfect world the API would have webhooks I could use to watch for data changes but that's not an option. Is my best bet to just optimize the factors I control to … -
when creating a record an error is declared: NOT NULL constraint failed: faq.user_id but the user was declared in views
As you can see form.user = request.user is declared after p fom.save(commit=false), but the error persists. can anybody help me? either with request.user or without request.user the error persists. remembering that I'm logged in as admin, and in /admin the functionality works correctly, inserting null=True creates the record but the functionality is not correct. models.py from django.db import models from django.utils import timezone from .. import settings class Faq(models.Model): CAT_FAQ_CHOICES = ( (0, 'Selecione'), (1, 'FAQ Todos'), (2, 'FAQ Psicologo'), (3, 'FAQ Paciente'), (4, 'FAQ Empresa'), ) idfaq = models.AutoField(primary_key=True) titulo = models.CharField( verbose_name='Titulo da Dúvida', max_length=100, null=False, blank=False) descricao = models.TextField( verbose_name='Descrição', null=True, blank=True) data_cadastro = models.DateTimeField( verbose_name='Data de Cadastro', auto_now=True) is_active = models.BooleanField('Ativado | Desativado', default=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) tipofaq = models.IntegerField(choices=CAT_FAQ_CHOICES,default=0) def __str__(self): return self.titulo class Meta: db_table = 'faq' verbose_name = 'faq' verbose_name_plural = 'faqs' views.py @login_required def criar_faq(request): if request.user.is_paciente: form = FaqForm(request.POST or None, initial={ 'user': request.user.paciente, 'tipofaq': 3}) custom_template_name = 'area_pacientes/base_paciente.html' if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect('faq:listar_faq') else: print(form.errors) return render(request, 'area_administrativa/faq/novo-faq.html', {'form': form, 'custom_template_name': custom_template_name}) elif request.user.is_psicologo: form = FaqForm(request.POST or None, initial={ 'user': request.user.psicologo, 'tipofaq': 2}) custom_template_name = 'area_psicologos/base_psicologo.html' if form.is_valid(): form = form.save(commit=False) form.user … -
Django model with a type field and lots of custom logic
I have a Django model that has a type field: class MyModel(models.Model): type = models.CharField(choices=MyModelTypes.choices) ... def some_func(self): if self.type == "TYPE_1": do_something_1() elif self.type == "TYPE_2": do_something_2() This is getting really complicated and is causing conditionals to be littered everywhere, so I'm wondering if there's some way to cast my model into some specific object that has a specific implementation of that some_func() function for the type.: class MyModelTypeA: ... class MyModelTypeB: ... class MyModel(models.Model): type = models.CharField(choices=MyModelTypes.choices) ... def some_func(self): # Obviously this won't work, but I want something that allows me to turn # MyModel into the right type then call the `some_func()` (which has logic # specific to the `type`). MyModelType(self).some_func() Or maybe that's the wrong approach. Any ideas? -
When Django Form is Invalid, why only file type input is rest?
If there is an invalid field after submitting my Django Form, the other fields have input values when submitted, but only the inputs of the file type will be emptied. I don't think there's anything to change in Dajngo. Perhaps this is a characteristic of html file type input? For example, my form compresses video files uploaded by users. And it takes quite a bit of time. If something goes wrong after submitting the form, the user must select the file again and proceed with the compression process. This is not good. Forms.py class VideoArtUploadForm(forms.ModelForm): class Meta: model = models.VideoArt fields = ( "video", "thumbnail", "poster", "title", "year", "artist", "description", ) widgets = { "video": forms.FileInput(attrs={"accept": "video/mp4"}), "title": forms.TextInput(attrs={"placeholder": "Il titolo del video"}), "year": forms.TextInput( attrs={"placeholder": "l'anno in cui il video è uscito"} ), "artist": forms.TextInput(attrs={"placeholder": "Il nome di artista"}), "description": forms.Textarea( attrs={"placeholder": "una descrizione del video "} ), } def clean_thumbnail(self): thumbnail = self.cleaned_data.get('thumbnail') if thumbnail: if thumbnail.size > 10*1024*1024: raise forms.ValidationError("Thumnail si deve essere meno di 10MB") return thumbnail else: raise forms.ValidationError("Thumnail è necessario") def clean_poster(self): poster = self.cleaned_data.get('poster') if poster and (type(poster) != str): if poster.size > 10*1024*1024: raise forms.ValidationError("Cover image si deve essere meno di 10MB") … -
How best to validate number of total reverse relationships before saving
I have an Item model that is reverse-related to two other models (ItemComponent and or ItemComponentCategory). The idea is I'd like to be able to validate that Items have no more than 4 relations to the two other models, combined, before being saved. class Item(models.Model): name = models.CharField(max_length=40, unique=True) class ItemComponent(models.Model): parent_item = models.ForeignKey(Item, related_name='components') class ItemComponentCategory(models.Model): parent_item = models.ForeignKey(Item, related_name='categories') I'd like to create a validation that raises an error before saving either the Item, ItemComponent, or ItemComponentCategory objects if the saved objects will result in > 4 object relations between them. I have tried adding something like this to the clean methods for all three: def clean(self): if (self.parent_item.components.count() + self.parent_item.categories.count()) > 4: raise ValidationError(_(f'Items can have no more than 4 components and/or component categories')) This seems to work as long as the Items and their relations are already saved and you're trying to add more relations. However, if I create a TabularInline in the ItemAdmin to add these 'sub types,' if you will.. I can create a new Item and add as many of these sub types and save it no problem. What am I missing here? -
Django SelectDateWidget
date_range = 100 this_year = date.today().year birth_date= forms.DateField(label='What is your birth date?', widget=forms.SelectDateWidget(years=range(this_year - date_range, this_year+1))) I would like to only select dates 100 years from today. But I currently can get values like Dec 31 2021 where sometimes the months and days don't match the correct values. -
Convert text to list of Strings Python
How can i convert these lines in a .txt file into a list of strings (each list item is a row in the text file): great dane saint bernard, st bernard eskimo dog, husky malamute, malemute, alaskan malamute siberian husky the code I did does the split , but make no consideration for the comma! Meaning , I want to split based on the comma , not only the line. This is the code I did. with open(dogfile) as file: lines = file.readlines() dogs_list = [line.rstrip() for line in lines] -
Django returning "CSRF verification failed. Request aborted. " behind Nginx proxy locally
I'm running a simple Django application without any complicated setup (most of the default, Django allauth & Django Rest Framework). The infrastructure for running both locally and remotely is in a docker-compose file: version: "3" services: web: image: web_app build: context: . dockerfile: Dockerfile command: gunicorn my_service.wsgi --reload --bind 0.0.0.0:80 --workers 3 env_file: .env volumes: - ./my_repo/:/app:z depends_on: - db environment: - DOCKER=1 nginx: image: nginx_build build: context: nginx dockerfile: Dockerfile volumes: - ./my_repo/:/app:z ports: - "7000:80" ... # db and so on as you see, I'm using Gunicorn the serve the application and Nginx as a proxy (for static files and Let's Encrypt setup. The Nginx container has some customizations: FROM nginx:1.21-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d And the nginx.conf file is a reverse proxy with a static mapping: server { listen 80; location / { proxy_pass http://web; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /app/my_repo/static/; } } Running this on the server after setting up let's encrypt in the Nginx container works without any issue, but locally I get the "CSRF verification failed. Request aborted." error every time I submit a form (e.g. create a dummy user in Django Admin). I … -
Updating admin/staticfiles with Django
I am having trouble with updating the css, img, fonts, and js admin files when I upgrade Django. I first noticed this when I upgraded to Django 2.0 (see here), and now the problem is worsening as I upgrade to 4.0. The backend functionality is working perfectly well. But now when I access the admin console, the homepage remains on the top of the browser page, even when I navigate to different models. I noticed that none of the /static/admin/ files (css, js, img, fonts) were updated on my local machine when upgrading from Django 2.2.24 to 4.0. Should I have expected these files to update along with Django? Am I missing a step to ensure that the admin static files are updated to reflect the newest version of Django? -
How to create a dynamic dependent form select options data model in django
I am new to django. I'm trying create an ecommerce application in which the user will select from a category of options [automobile, property, electronics, phones, clothes etc], and upon selecting an option (say automobile), the next select field options will be populated asking for model [Honda, Toyota, Chrysler etc], if user select say Toyota, a list of Toyota models comes up [Camry, Highlander, Corolla, etc.], upon selecting say Camry, another set of options comes up asking for year, and so on. How do I implement (generate and/or store) this type of data using django models? I'll be very grateful for a swift response to this. Thank you. -
Why DRF shows Forbidden (CSRF cookie not set.) without @api_view(['POST'])?
I'm using django-rest-framework(backend) and react(frontend). In react i created a login form ,when i submite the form it sends an axios.post to my view function. The problem is django raise a error and the message: Forbidden (CSRF cookie not set.) My axios: axios({ method:'post', url: url, data:{email:email, password1:senha}, headers: {'X-CSRFTOKEN': token}, withCredentials: true }) .then((response)=>{ console.log(`Reposta: ${response.data}`) }) .catch((error)=>{ console.log(`Erro: ${error.data}`) }) My django view: def login_usuario(request): if request.method == 'POST': return HttpResponse('Something') Obs1:If i include de @api_view(['POST']) decorator works, but i want to know if is possible make the request without it. Obs2: When my react form render, a function that creates a csrf_token was called, so the csrf_token its being sent but django isn't reading it -
Python - "cannot unpack non-iterable int object" when importing json data into database
I'm working on an importer to import a list of facilities from a json file into my database. The importing works. But when i added some extra conditions to update existing facilities (whenever i run the script again and there is updated data inside the json) it stopped working the way it originally did. The updating works if i only have 1 facility inside the json file but if i add more than one i get the following error: cannot unpack non-iterable int object Also: Instead of updating it will just create two additional copies of one of the facilities. Been trying to figure this out for a couple of days now but so far no luck. import_facility_from_file.py import os import json from data_import.models import Facility, FacilityAddress, FacilityInspectionInfo, FacilityComplaints from django.core.management.base import BaseCommand from datetime import datetime from jsontest.settings import BASE_DIR, STATIC_URL class Command(BaseCommand): def import_facility_from_file(self): print(BASE_DIR) data_folder = os.path.join(BASE_DIR, 'import_data', 'resources') for data_file in os.listdir(data_folder): with open(os.path.join(data_folder, data_file), encoding='utf-8') as data_file: data = json.loads(data_file.read()) for key, data_object in data.items(): UUID = data_object.get('UUID', None) Name = data_object.get('Name', None) IssuedNumber = data_object.get('IssuedNumber', None) Capacity = data_object.get('Capacity', None) Licensee = data_object.get('Licensee', None) Email = data_object.get('Email', None) AdministratorName = data_object.get('AdministratorName', None) TelephoneNumber = … -
Python Package Download in offline environment :( ('typing_extensions-4.0.1')
I'm trying to run a Django Application in an offline internal network environment. I have a problem in the process of downloading requirements for this. Currently, I'm installing Python packages using the 'setup.py install' command. However, there is no setup.py file in the 'typing_extensions-4.0.1' package, so it's impossible to download the package. I want to ask for advice on how to solve it. For your information, 'conda', 'pip' conmmands are not available. -
Django - UnboundLocalError: local variable 'image_link' referenced before assignment
I have written a function for parsing news articles feeds. def save_new_articles(feed, source_id, category_id): channel_feed_title = feed.channel.title.title() channel_feed_link = feed.channel.link channel_feed_desc = feed.channel.description official_source_id = source_id post_category_id = category_id for item in feed.entries: parsed_summary = item.summary soup = BeautifulSoup(parsed_summary, 'lxml') images = soup.findAll('img') for image in images: image_url_link = (image['src']) if image_url_link is not None: image_link = image_url_link else: image_link = "https://www.publicdomainpictures.net/pictures/280000/velka/not-found-image-15383864787lu.jpg" parsed_title = item.title formatted = re.sub("<.*?>", "", parsed_title) post_title = formatted post_link = item.link description = item.description output_summary = re.sub("<.*?>", "", description) title = item.title capital = title.title() tags = capital.split() date_published = parser.parse(item.published) if not Posts.objects.filter(guid=item.guid).exists(): post = Posts( title = post_title, link = post_link, summary = output_summary, image_url = image_link, tags = tags, pub_date = date_published, guid = item.guid, feed_title = channel_feed_title, feed_link = channel_feed_link, feed_description = channel_feed_desc, source_id = official_source_id, category_id = post_category_id ) post.save() else: logger.info("Duplicate Post Detected! Skipping...") But upon running the code I get: image_url = image_link, UnboundLocalError: local variable 'image_link' referenced before assignment I don't understand where the error is coming from seeing as I had defined image_link in the image for loop statement above. I have checked similar answers on SO but I don't seem to find a suitable answer. … -
Django: using AJAX for login, how do (should) I update a form's CSRF Token?
Context: A company project I am working on is using AJAX to log a user in for certain actions on the webpage. This webpage can be viewed without logging in, but certain actions need authentication (like updating the settings of a piece of hardware). I want to preserve the form the user currently has so they don't have to re-input their changes (which I am currently doing by hiding the form and overlaying a "login" form) so refreshing the page is not an option, or at the very least, a last resort. The issue: After the login has completed, the CSRF token of the first form is now invalid and needs to be updated. This is not a question of "how do I add a CSRF token to an AJAX request", but a "how do I update it". Django is throwing the following error after logging in: Forbidden (CSRF token from POST incorrect.) Here's what I've already tried: Sending a new CSRF token for the form after logging in (server-side): form = AuthenticationForm(data=request.POST or None) if form.is_valid(): # Login the user user = authenticate( username=form.cleaned_data.get("username"), password=form.cleaned_data.get("password"), ) if user is not None: login(request, user) # Neither of these have worked … -
Django Multi Step Form
Currently my sign up for all users is currently working but I want to add 2 buttons before it that will sign up differently based off which element they clicked. Use normal sign up if it's User and use another for Doctor. 2 users: Doctor and User. <html> <body> <button>Doctor</button> <button>User</button> </body> </html> models.py: is_doctor -> a boolean has_credentials -> verifies doctor a file upload -> wants admin to verify before adding signup.html(displays on http://localhost:8000/signup/) {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> <a href="{% url 'login' %}">Log In</a> </form> {% endblock %} views.py from django.shortcuts import redirect, render from .forms import SignUpForm, UserProfileForm from django.contrib.auth import login, authenticate def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) forms.py from django import forms from django.core.files.images … -
Django and Jquery Autocomplete Issues
I know there are several posts regarding autocomplete and django, but I'm recently entering in to the realm of jquery and somehow I'm lost. As you can imagine, I need an autocomplete for the following field: HTML file <div class="ui-widget"> <input name="user_name"class="form-control "id="company-search"> </div> <script type="text/javascript"> $(function() { $("#company-search").autocomplete({ source: '{% url 'autocomplete' %}', minLength: 1, }); }); </script> URL path('autocomplete/',views.autocomplete, name='autocomplete') Views def autocomplete(request): data = request.GET['term'] forecast = LeadEntry.objects.select_related('lead_id') companies = [str(i.lead_id.company).lower() for i in forecast] search = [i for i in companies if i.startswith(data.lower()) ] result = [] for company in search: data = {} data['label'] = company data['value'] = company result.append(data) print(json.dumps(result)) mimeetype='application/json' return HttpResponse(json.dumps(result),mimeetype) Please note that the ajax portion works well, I can see the view working every time, I type a new letter, I'm getting a json file with the correct data. My real struggle is that I can't display it in my HTML, how do I send back that data an added to the same field, ideally, I want to be able to get a drop down list? I'm getting the following errors on the javascript side: Regards -
django - custom storage url
I have a dropbox storage class inheriting Storage (see below). The thing is url method is going to run on each image render, causing back and forth to Dropbox API which seems kind of unnecessary. Would it be correct to instead move the shared link functionality in _save instead and store the URL in the name attribute (varchar in DB) and leave url() blank? class DropboxStorage(Storage): def __init__(self, options=None): if not options: options = settings.CUSTOM_STORAGE_OPTIONS self.d = dropbox.Dropbox(options['DROPBOX_KEY']) def _open(self, name, mode='rb'): with open(name, mode=mode) as f: return File(f, name) def _save(self, name, content): meta = self.d.files_upload( content.read(), f'/Images/{name}', autorename=True) return meta.name def url(self, name): link_meta = self.d.sharing_create_shared_link(f'/Images/{name}') return link_meta.url.replace('dl=0', 'raw=1') # no need to implement since files_upload will take care of duplicates def exists(self, name): return False -
How to pass data on django ajax?
how to pass filter data from Django model/view to ajax? I tried to pass the data but, it's showing no result. The ajax return field is blank. From the request get method I tried to post the data, that's working fine. With the ajax method, I tried to do as follows, but it's throwing just a blank area. I tested on console, the filter value is correctly passed to views but from views, it's not fetching correctly. Is it an ajax success problem or do my views has any other issue? Please help me My HTML: <ul class="widget-body filter-items "> {% for categories in categories%} <li class = "sidebar-filter " data-filter="category" data-value="{{categories.id}}" ><a href="#">{{categories.name}}</a></li> {% endfor %} </ul> <div class="product-wrapper row cols-lg-4 cols-md-3 cols-sm-2 cols-2"> {% for product in products%} <div id = "product-wrapper" class="product-wrap product text-center"> {{product.name}} {% endfor%} </div> </div> Ajax: $(document).ready(function () { $('.sidebar-filter').on('click', function () { var filterobj= {}; $(".sidebar-filter").each(function(index, ele){ /**var filterval = $(this).attr('data-value');*/ /**var filterval = $(this).value=this.attr('title');*/ /**var filterval = $(this).val($(this).text());*/ var filterval=$(this).data("value"); var filterkey = $(this).data('filter'); filterobj[filterkey]= Array.from(document.querySelectorAll ('li[data-filter=' + filterkey+'].active')).map(function(el){ /**return $(el).data("value");*/ return $(el).data("value") /** return el.getAttribute('data-value');*/ }); }); console.log(filterobj) $.ajax ({ url:"/products/filter-data", data:filterobj, datatype:'json', success:function(res){ console.log(res.data) var bodyOnly = $(res.data).find('.product-wrapper').html(); $('.product-wrapper').html(bodyOnly); … -
Is the implementation of Django code into HTML possible?
HTML File: <script> from django.contrib import messages messages.error('Sign-In First') </script> This doesn't work but is there a way where I can do this? Because my layout of an error message is not appealing as compared to Django's. -
How protect Login and Register endpoints (views) of an API created with DRF which use JWT as authentication?
I have been searching and reading other questions and blogs, but I didn't find anything concrete about my doubt. A little of context: I am developing a SPA which works with a REST API in Django by means of Django Rest Framework (DRF) and the authentication is made it through Bearer token: JWT (package 'Simple JWT'). So, I was reading whether it needs protection against CSRF: • Do I need CSRF token if I'm using Bearer JWT? • Should I use CSRF protection on Rest API endpoints? • The Web API Authentication guide, Bearer tokens Basically if the browser does not make an automatically authentication (with sessions or some kind of cookie), the odds of a CSRF vulnerability are slim. This approach is achieved with the Bearer Tokens using the JWT. The problem: There are some public endpoints, that don't need authentication, so I used this permission in DRF settings 'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.IsAuthenticatedOrReadOnly'], This way, unauthorized users only can make safe requests -methods: GET, HEAD and OPTIONS-. The users, with a JWT, can perform any kind of request. Login and register views works through POST requests due to modify the state of the application. The issue is the above permission avoids … -
django-background-tasks process_tasks not working
I've set up a django project with the instructions from the docs, and have a simple task: @background def test_task(): print("wtf") I then ran the test_task() function within the manage.py shell, and the task was successfully added to the DB (SQLite3). However, when I ran python manage.py process_tasks nothing happened. This module isn't very popular to say the least, so I couldn't find any answers to my problem until 5 minutes ago on a closed issue on the module's repository on github. And I am deciding to post this below. PS: I am running Django 2.2 for this project -
Django - Dividing a modelform into sections
I am making a property management app where the user can fill out a rental application. I'm looking for a way to divide my form into sections like Personal Information: item item item item Rental History: item item item item Employment item item item My form class ApplicantForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ApplicantForm, self).__init__(*args, **kwargs) self.fields['property'].queryset = Properties.objects.filter(is_active=True) class Meta: model = Applicant fields = '__all__' exclude = ['application_date'] widgets = { 'requested_move_in_date': DateInput(), 'dob': DateInput(), 'job_length': DateInput(), } labels = { 'requested_move_in_date': 'Requested Move in Date', 'dob': 'Date of Birth', 'ssn': "Social Security Number", 'job_length': "Job Start Date" } My template {% load crispy_forms_tags %} {% block content %} <div class="jumbotron text-center"> Application page </div> <form class="post-form" method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="save btn btn-primary">Submit</button> </form> {% endblock %} -
Django - Detecting Value of Field in Model - Views
I need to loop through all field objects of a model in Django. Once I look through I need to detect if in any of the entries of data this specific field(type) is equal to "Date1". If it is I need it to send a variable(val) that is a string equal to "True" to the Django templates. I have everything set and it seems simple and it seems like it should work. On its own, the val can send a value to the template when it is not in an if statement and the for loop also properly works. Even when "Date1" exists as a value in the type field of an entry in the model "Field_Repo1" the val isn't sent and the if statement is never iterated through(I know this by using prints). No matter what the if statement is never run through. Code Below. Thanks in advance. context = {} context['Field_Repo1'] = Field_Repo1.objects.filter(user=response.user) for type1 in Field_Repo1.objects.values_list('type'): if type1 == "Date1": val = "True" context['val'] = val print(val) print(AHHHHHHHHHHHH) if response.method == 'POST': form = Field_Repo1_Form(response.POST, response.FILES) if form.is_valid(): instance = form.save(commit=False) instance.user = response.user instance.save() response.user.Field_Repo1.add(instance) return redirect('repo1') else: form = Field_Repo1_Form() context['form'] = form return render(response, …