Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - passing one model to another while creating new object
My site has multiple tests with multiple questions each. I'd like to make question creation form which will have preset test object depended on url. it's better explained in comment in views.py That's what I have already done; models class Test(models.Model): name = models.CharField(max_length=200) #questions = models.ManyToManyField(Question) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True) date_posted = models.DateTimeField(auto_now_add = True) def get_questions(self): return self.question_set.all() def __str__(self): return self.name class Question(models.Model): text = models.CharField(max_length=200, null=True) test = models.ForeignKey(Test, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add = True) def __str__(self): return self.text urls urlpatterns = [ path('', views.home, name='home'), path('test/<str:pk>/', views.test), path('test/<str:pk>/question-create/', views.QuestionCreateView, name='question-create'), ] forms from django import forms from django.forms import ModelForm from .models import Question, class QuestionCreationForm(ModelForm): class Meta: model = Question fields = '__all__' /// all except test which is set by pk in url views def QuestionCreateView(request, pk): form = QuestionCreationForm() if request.method == 'POST': test = Test.objects.get(id=pk) /// I would like to pass it to models to disallow user to choose to which test will question belong, i mean test should pe preset by <pk> in link form = QuestionCreationForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form':form} return render(request, 'exam/question_form.html', context) what should I add/change to disallow user to … -
Import could not be resolve after installing the dependency
I'm trying to install de messagebird dependency into my python project. I write into requirements.txt and after I run pip install -r requirements.txt as you can see below: But the pylance was still showing me the error: Then I try to install using pip install messagebird but still with no success. I also try to reopen the window but no success too. -
Django : TemplateSyntaxError("Could not parse the remainder: '%s' "
I notice that Django can't get to the elements from context dictionary with have extra symbols like '^,=', is there anyway to solve this? raise TemplateSyntaxError("Could not parse the remainder: '%s' " django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '^SPX' from 'price.^SPX' {{ price.^SPX }} def home(request): tk_stocks=["^IXIC","^SPX","^DJI"] yahoo_financials_tech = YahooFinancials(tk_stocks) p_change=yahoo_financials_tech.get_current_percent_change() change=yahoo_financials_tech.get_current_change() price=yahoo_financials_tech.get_current_price() context={ "p_change":p_change, "change":change, "price":price } print(price) return render(request, 'home.html', context) -
Am I handling users' passwords safely(Django + Gunicorn HTTP vs HTTPS)?
I have a django website running the django-auth package to let users register and sign in. I haven't changed anything about how django-auth implements register and sign in, so there should be no issues there. I'm running my server through gunicorn, and after setting up SSL and changing port to 443, I noticed that when you type example.com there's no response because the server isn't running on http anymore, only https. I searched around for solutions and it said I had to set up nginx or a reverse proxy of some sort, I've decided to skip that step and maybe set it up later. What I did was run two instances of gunicorn, one on port 80 and one on port 443. Then I ran some code to redirect the http traffic to https traffic: if request.scheme is 'http' and settings.DEBUG is False: return HttpResponseRedirect('https://example.com') I know this is probably a bad idea, and I should really switch to nginx soon, I'm not concerned with any performance losses yet or any security losses since I don't carry any sensitive data EXCEPT for the users' passwords. All I want to know is, does just having an http version of the website … -
Django Admin change page: How can I put the save button set on the left, and delete button on the right?
Currently, I have the default setting. How can I switch the positions of the save button sets and delete button while not affecting the mobile css layout (which I like to remain as itself)? What is the best way doing it? Thank you! -
How can I delete a data on db automatically after 24 hours in django?
I want to make an instagram clone with django. I'm trying to make stories of instagram on Django Models.As you know, instagrams stories are deleted after 24 hours. How can i delete data from database? -
Can I have a django loading animation while a view is being processed?
I have a view which has a form for a zipcode input, it then takes some time to run a function Scrape_by_zip. It returns a download link to an excel file once complete. While this function is processing I don't want the user to think nothing is happening. Is there a way I can get a loading bar or animation while this is going on? Another possibility is the user gets redirected to another page and shows a "Please wait for download" message, but I am not sure how to go about this approach either. Below is my view. def scrapeComplete(request): if request.method == 'POST': try: zip_code = request.POST['zip_code'] print(zip_code) df = Scrape_by_zip(int(zip_code)) with BytesIO() as b: # Use the StringIO object as the filehandle. writer = pd.ExcelWriter(b, engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save() # Set up the Http response. filename=str(zip) +" Properties" +".xlsx" response = HttpResponse( b.getvalue(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) response['Content-Disposition'] = 'attachment; filename=%s' % filename return response except: return HttpResponse('Error') return HttpResponse('Error') -
How to serve static files from Django using docker-compose and Nginx?
I am trying to serve static files from Django using docker-compose and Nginx. I have a compose file where I set up the three services as well as volumes for the database, static files and uploaded files: version: '3' services: lims: container_name: lims build: ./lims env_file: - ./lims/.env.django.prod ports: - '8000:8000' depends_on: - db volumes: - static_volume:/lims/staticfiles - upload_volume:/lims/upload db: image: postgres:13.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./lims/.env.db.prod nginx: container_name: nginx restart: always build: ./nginx ports: - "80:80" volumes: - static_volume:/lims/staticfiles - upload_volume:/lims/upload depends_on: - lims volumes: postgres_data: static_volume: upload_volume: Now if I run this with Django's DEBUG=1 everything works fine. However as soon as I turn the Debug mode off, all static files are gone. In the Django settings I specified the static and uploaded files location like this: MEDIA_URL = '/lims/upload/' MEDIA_ROOT = BASE_DIR / 'upload' STATIC_URL = "/lims/staticfiles/" STATIC_ROOT = BASE_DIR / "staticfiles" I also tried to add the path /lims/staticfiles/ to Nginx like this: location /lims/staticfiles/ { alias /var/lib/docker/volumes/; } as I believe the volumes should be located there. However this actually lead to the static files not even appearing in Debug mode. How do I correctly serve my static files and user uploaded content here? -
Django if created new object
I will running something function if created new object. But i will not run if the object already exists Example: class Model(models.Model): test = models.Charfield(max_length=255) if created new object(!): requests.POST(blablabla) -
Django forms select option value hand to same URL
I am having trouble figuring out how get the selected option of a form handed back to the same url as a get context value: forms.py class ModeForm(forms.Form): MODES = ( ('','Select a generation mode'), ('docker','Docker'), ('docker-compose','Docker Compose'), ('kubernetes', 'Kubernetes'), ) selectedMode = forms.CharField(label="", widget=forms.Select(choices=MODES, attrs={ 'class': 'form-control', 'placeholder': 'Generation mode', 'onchange': 'form.submit();', }), ) views.py # Home page def viewHome(request): if request.method == 'POST': currentMode = request.POST.get('selectedMode') form = ModeForm(initial={'name':currentMode}) print(f"Post Mode is: {currentMode}") context = { 'data': None, 'form': form, } return render(request, 'main/home.html', context) I can obtain the selected value on the POST to the view. However, I am not sure how to have that selection remain once the selection has been made and the form is displayed again. As things are now: The select field has an initial value when the home page is initially loaded. Once a value is selected, the form is posted to the home page. In the request.POST I can get the selected value. However, the select control resets and the value is lost outside of the POST. What I am attempting to do is, get a selection on form submission. Have that value persist once a value is set. Is there … -
how to custom form errors in view
I am using this code to check how many images are being uploaded and the size of the image. Currently i am using a ValidationError but it looks like this in development and in production is just throws a 500 server error. How can I have it throw a form error that looks something like this I was using the messages framework as a work around but would much rather do it the proper way. Must be achieved in the view. code: if len(request.FILES.getlist('images')) > 3: #messages.error(request, 'More than 3 images') raise ValidationError(f'More than 3 images') for image in request.FILES.getlist('images'): if image.size > settings.MAX_UPLOAD_SIZE: raise ValidationError(f'Image {image} is too large 3mb max') -
database synchronization between sql server windows form c#.net app and Django sqllite on web server
I have a windows form application which wrote with net framework and it has local database sql local db its install in many client side and now i develop web based application with Django python . so i need suggestion with one function and its database synchronization between the local database and server database i want that all user store the data on local system so once they got internet they sync it with server database also and i dont want to delete the local data after its sync i need its be on both side so should i use REST API for this or there is another method also which is better that i use them . -
Django reusing class based views and adding arguments
Still getting used to Django and how they approach their view classes so bear with me. My current project setup is using several apps all using the same view classes just with a different database. Ideally, I would like to have one class that I can call for other apps views.py using From helperclasses import Browse view = Browse.as_view() return view(request) My question is how can I pass an argument to the imported class such as the database to use. For example, something like below From helperclasses import Browse view = Browse(database_to_use).as_view() return view -
How to use model form instance in Django template
I'm trying to access the instance of the forms in a formset, but it is not working. I CAN access them using the variable notation, as in {{ form }}, but not in code, as in {% url 'section' form.instance.pk %}. I need to iterate through the forms in the formset along with the corresponding model instance. My view: # views.py def sec(request, companyurl): company = get_if_exists(Company, author=request.user) SectionFormSet = modelformset_factory(Section, form=SectionForm, can_delete=True) sections = Section.objects.filter(company=company).order_by('order') formset = SectionFormSet(request.POST or None, initial=[{'company': company}], queryset=sections context = { 'sections': sections, 'formset': formset, } return render(request, 'questions/sections.html', context) My model: # models.py class Section(models.Model): section = models.CharField(max_length=100) company = models.ForeignKey(Company, on_delete=models.CASCADE) order = models.PositiveIntegerField(default=1000000) show = models.BooleanField(default=True) def __str__(self): return self.section My Form (I'm using django-crispy forms): # forms.py class SectionForm(forms.ModelForm): class Meta: model = Section fields = ['company', 'section', 'show', 'order'] labels = { 'section': '', 'show': 'Show' } def __init__(self, *args, **kwargs): super(SectionForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Div( Div(HTML("##"), css_class = 'my-handle col-auto'), Div('section', css_class='col-3'), Div('show', css_class = 'col-auto'), Div('DELETE', css_class = 'col-auto'), Field('company', type='hidden'), Field('order', type='hidden'), css_class='row', ), ) My template (this is where the problem is seen): <form action="#" method="post"> {% … -
Using HTTP_408_REQUEST_TIMEOUT for POST request
I am implementing a post request for an image tagging game and need to set a timeout after 5 minutes after the game round has been created: views.py def post(self, request, *args, **kwargs): gameround = Gameround.objects.all().get(id=request.data) tag_serializer = TagSerializer(data=request.data) tagging_serializer = TaggingSerializer(data=request.data) if gameround.created + timezone.timedelta(minutes=5): if tagging_serializer.is_valid(raise_exception=True): tagging_serializer.save(tagging=request.data) return Response({"status": "success", "data": tagging_serializer.data}, status=status.HTTP_201_CREATED) else: return Response({"status": "error", "data": tag_serializer.errors}, status=status.HTTP_400_BAD_REQUEST) else: return Response(status=status.HTTP_408_REQUEST_TIMEOUT) Testing the post request in Postman yields the following TypeError: Field 'id' expected a number but got {'gameround_id': 2015658021, 'resource_id': 102209, 'tag': {'name': 'PERSON', 'language': 'en'}}. How can I get rid of this and make the timeout work? -
Normalise models the correct way
I have 4 models Profile, Product, Holding and Transaction. A user (profile) can assign products to their account. I then want the user to be able to add a transaction to the product, i.e they can add 10 of the product and the price they paid, which will then be presented in a table showing the total amount they hold as well as the average price. But im not sure if what i am doing is correct in terms of the FKs and MtM fields. class Product(models.Model): name = models.CharField(max_length=255, blank=False, unique=True) slug = models.CharField(max_length=50, blank=True,null=True) symbol = models.CharField(max_length=50, blank=True,null=True) price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) capture_date = models.DateField(blank=True,null=True) logo_address = models.URLField(max_length=255, blank=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) website = models.URLField(max_length=50, blank=True) twitter = models.CharField(max_length=50, blank=True) meta = models.CharField(max_length=50, blank=True) github = models.CharField(max_length=50, blank=True) def __str__(self): return str(self.user) class Holding(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return str(self.product_name) class Transaction(models.Model): product = models.ForeignKey(Holding, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) price = models.FloatField(max_length=50, blank=True, null=True) transaction_date = models.DateField(null=True, blank=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) I was thinking that I could … -
How to configure Geopandas with Django
Im using this https://gist.github.com/linwoodc3/0306734dfe17076dfd34e09660c198c0 from github to convert a kmz file to shp file. It works fine when I run it using hardcoded file path. I want to integrate this into my web app which uploads kmz file using this function: #Models.py class FileDocument(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True)``` The file uploads fine into documents folder and has the same size and name as the file on my local computer, however when reading the kmz file using the aforementioned function I get the following error: *No geometry data set yet (expected in column 'geometry'.)* By printing the dataframes I can see that the geometry column is missing when I upload it through django, however rest of the attributes are there. I think this error has more to do with how Geopandas, Gdal, Geos and other spatial libraries are configured in Django vs my virtual environment. Any help or insight would be appreciated. Thank you! -
Check size of multiple uploaded files
I have a feature that allows users to upload multiple files. I want to check the size of these files and dissallow files that are too large images = request.FILES['images'].size if images > settings.MAX_UPLOAD_SIZE: raise Exception(f'Image {images} is too large 3mb max') I have been playing with this code but I cannot figure out a way to loop over all of the files. What confuses me about this is i am not iterating over all the files but it still properly throws the exception no matter what order the file that is too large appears in. Is this code working properly? -
Generating x number of React components from integer variable
So I have a webpage that's meant to model a sort of questionnaire. Each question would take up the whole page, and the user would switch back and forth between questions using the arrow keys. That part's fine, swapping components on button pressing doesn't seem to be an issue, and I got a proof-of-concept of that working before. The trouble is, these questionnaires won't have the same number of questions every time. That'll depend on the choice of the person making the questionnaire. So I stored the number of questions in a variable held in the Django Model, and I fetch that variable and try to generate x number of components based on that integer. At the moment I'm just trying to get it to generate the right number of components and let me navigate between them properly, I'll worry about filling them with the proper content later, because I'm already having enough trouble with just this. So here's my code: import React, { useState, useEffect, cloneElement } from 'react'; import { useParams } from 'react-router-dom' import QuestionTest from './questiontest'; function showNextStage(displayedTable, questionCount) { let newStage = displayedTable + 1; if (newStage > questionCount) { newStage = questionCount; } return … -
Django web deployed by pythonanywhere doesn't refresh automatically [closed]
I deployed my Django project with pythonanywhere and have already pushed it from localhost to the webserver. My Django project is linked with dynamic data from my google sheet API. However, when I edit on my google sheet and reload the page, the data doesn't change accordingly. I have to manually click the "reload" button on pythonanywhere to refresh my data. Does anyone know what should I do? -
How to post data to ModelForm while testing assertRedirects
I try to test correct redirect after post data with ModelForm. In my view if form.is_valid() equals True, form is saved and view redirects to homepage. My test_forms.py looks like this: class TestForms(TestCase): def setUp(self): # imitacja witryny self.client = Client() self.tag = Tag.objects.create( name='Bull flag' ) self.data = { 'ticker': 'FB', 'exchange': 'NASDAQ', 'buy_point': 121, 'stop_loss': 120, 'description': 'ciamciaramcia', 'tags': [self.tag] } self.form = StockTradeForm(self.data) def test_stock_trade_form_valid_data(self): self.assertTrue(self.form.is_valid()) # OK self.form.save() self.assertEqual(StockTrade.objects.count(), 1) # OK after self.form.save() self.assertTrue(StockTrade.objects.filter(ticker='FB').exists()) # OK after self.form.save() def test_stock_trade_form_valid_redirect(self): response = self.client.post(reverse('create-trade'), self.data) print(response) # print result: .<HttpResponse status_code=200, "text/html; charset=utf-8"> self.assertTemplateUsed(response, 'journal/create_trade.html') # OK self.assertEquals(response.status_code, 200) # OK self.assertRedirects( response, reverse('index'), status_code=200 ) # Failure: # in assertRedirects # url = response.url # AttributeError: 'HttpResponse' object has no attribute 'url' Shouldn't response = self.client.post(reverse('create-trade'), self.data) imitate valid and saved form? My view name is: create_trade Url looks like this: urlpatterns = [ path('', views.index, name='index'), path('display-trade/<str:pk>', views.display_trade, name='display-trade'), path('create-trade', views.create_trade, name='create-trade'), path('update-trade/<str:pk>', views.update_trade, name='update-trade') ] I'm concerned about this two tests self.assertTemplateUsed(response, 'journal/create_trade.html') # OK self.assertEquals(response.status_code, 200) # OK Is it correct that after self.client.post assertTemplateUsed response is equal 'journal/create_trade.html' and status_code is 200? I tried many things with self.client.post but nothing work … -
Django howto progessively write data into a huge zipfile FileField
I have a django model like this: class Todo(models.Model): big_file = models.FileField(blank=True) status = models.PositiveSmallIntegerField(default=0) progress = models.IntegerField(default=0) I'd like to do two operations: first make an empty zipfile out of big_file (less important) and then progressively add files into my zipfile (and save it iteratively) The overall process would look like that: from django.core.files.base import File import io, zipfile def generate_data(todo): io_bytes = io.BytesIO(b'') # 1. save an empty Zip archive: with zipfile.ZipFile(io_bytes, 'w') as zip_fd: todo.generated_data.save('heavy_file.zip', File(zip_fd)) # 2. Progressively fill the Zip archive: with zipfile.ZipFile(io_bytes, 'w') zip_fd: for filename, data_bytes in long_iteration(todo): with zip_fd.open(filename, 'w') as in_zip: in_zip.write(data_bytes) if condition(something): todo.generated_data.save() # that does not work todo.status = 1 todo.progress = 123 todo.save() todo.status = 2 todo.save() But I can't figure out the right filedescriptor / file-like object / Filepath / django-File object combination ... And it seems that in django I always have to save(filename, content). But my content could be Gigabytes, so it does not sound reasonable to store it all into a "content" variable? -
Django 'this field is required' form error on non-editable field
I'm trying to build a form that lets me categorise/edit my bank transactions. Ideally all uncategorised transactions will be displayed on one page (in a formset) and I'll be able to edit some/all of them. When I hit 'submit' on the formset, I want to save any changes and navigate to a confirmation page. Here's my model for a Transaction: class Transaction(models.Model): description = models.CharField(max_length=200) post_date = models.DateTimeField('date') account = models.ForeignKey(Account, null=True, on_delete=models.SET_NULL) category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL) amount = models.DecimalField(max_digits=9, decimal_places=2) uuid = models.CharField( max_length=200, primary_key = True, unique = True, editable=False) def __str__(self): return self.description Date, description, and amount are important to show on the form because they help me figure out how to categorise the transaction. I don't want to accidentally edit the date or amount, so I've made them readonly on the form. Transactions also have uuid and account fields, but those are irrelevant to categorisation and I don't want to edit them, so they shouldn't be shown at all. My form and formset look like this: class TransactionForm(ModelForm): class Meta: model = Transaction exclude = ('uuid', 'account') def __init__(self, *args, **kwargs): super(TransactionForm, self).__init__(*args, **kwargs) cat = self.fields['category'] cat.required = False cat.blank = True self.fields['description'] self.fields['amount'].readonly … -
save() prohibited [...] due to unsaved related object, but related object already saved
I'm working with Django 4.0.1. I'm having having "save() prohibited to prevent data loss due to unsaved related object 'page'" even if the 'page' object is saved one line before. Here is the code: # Upload entity data u = Upload( message=request.POST["upload_msg"] ) # saving u here to be able to use u.datetime later u.save() # new page for the upload entity page = Page( title="notes for Upload " + str(u.datetime), content="This page is empty..." ) page.save() u.page = page u.save() The last line (u.save()) is the one causing the error. Am I having some kind of race condition here? Isn't it assured that the previous db operations are complete before trying to run the next? Any other ideas? Thank you. -
Virtual Trading Platform with Django Rest Framework (Good Idea)?
Trading application relies on many requests is it advisable to build the API backend with Django rest framework with scalability in mind? Any suggestions would be great.