Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why won't my Django template display the correct date listed in the database?
My model contains a datefield, 'valid_until'. Even though an entry contains the date '12/25/2022', the update template literally displays as its contents 'mm/dd/yyyy' when the user tries to modify the date. Why? Also, there seems to be no way to create a placeholder text or even change that date format (it always renders in that same format---even though I specify '%m/%d/%y' in forms.py and settings.py contains the format '%m/%d/%y'). Why? settings.py: TIME_ZONE = 'US/Eastern' USE_I18N = True USE_L10N = True DATE_INPUT_FORMATS = '%m/%d/%y' models.py: class DecisionsList(models.Model): summary = models.CharField(default="", max_length=75, ` verbose_name="Decision Summary") description = models.CharField(max_length=100, verbose_name="Decision Description") valid_until = models.DateField(default=timezone.now, verbose_name="Voting End Date") date_created = models.DateTimeField(default=timezone.now) views.py: class UpdateDecisionView(LoginRequiredMixin, UpdateView): model = DecisionsList form_class = DecisionForm template_name = "users/update_decision.html" forms.py: class DecisionForm(forms.ModelForm): class Meta: model = DecisionsList fields = ['summary', 'description', 'valid_until'] widgets = { 'valid_until': forms.DateInput( format='%m/%d/%y', attrs={'type': 'date', 'placeholder': "Select a date" }), 'description': forms.Textarea( attrs={'line-height': '50px', }) } update_decision.html: {% extends "users/base_users.html" %} {% load crispy_forms_tags %} {% load crispy_forms_filters %} <body> {% block content %} <div class="nav"> <a id="company" {% block company %} class="selected" {% endblock %} href=""></a> </div> <div class="containers database-containers"> <h2>Update a Decision</h2> <form method="post"> <div class="form-group"> {% csrf_token %} {{form.summary|as_crispy_field}} <div class="text-area"> … -
Django @sync_to_async function can be used on uwsgi env?
I want to use @sync_to_async function on django. According to the Django Asynchronous support Document, Async views will still work under WSGI. Does this mean that "@sync_to_async" can also be used without adding the asgi env on uwsgi env? Also according to the documentation, it says Under a WSGI server, you will not get the benefits of an async stack.. What I want to do is add a lot of data through orm and add a lot of data to the queue. This operation is network io-intensive. Doesn't this need the benefit of the async stack? -
Django: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)
I'm trying to email using Python's smtplib. This is the email() function: def email(to, subject_parameter, body_parameter): subject = subject_parameter body = body_parameter sender_email = "pfcbookclub@gmail.com" receiver_email = to password = "Zt2.~[3d*.[Y5&5r" # Create a multipart message and set headers message = MIMEMultipart() message["From"] = sender_email message["To"] = receiver_email message["Subject"] = subject message["Bcc"] = "pfcbookclub@gmail.com" # Add body to email message.attach(MIMEText(body, "plain")) text = message.as_string() # Log in to server using secure context and send email context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, text) When someone signs up on my website, I want an email to be sent to the website's email address (not to the user). I've done this: def register(request): registered = False ctx = {} if request.method == 'POST': username = request.POST.get("username") full_name = request.POST.get("full_name") password = request.POST.get("password") email_id = request.POST.get("email") house_number = request.POST.get("house_number") phone_number = request.POST.get("phone_number") if len(User.objects.filter(username=username)) == 0: ctx["username_exists"] = False user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() user_profile = UserProfileInfo(user=user,full_name=full_name, email=email_id, house_number=house_number, phone_number=phone_number) user_profile.save() subject = username + " just registered" body = username + " just registered on pfcbookclub.com. Link to admin: https://pfcbookclub.com/Caput_Draconis/" email("pfcbookclub@gmail.com", subject, body) # Error on this line username = request.POST.get('username') … -
Сохранение формы, связанной с внешним ключом, в Django
Моя модель: class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) phone = models.CharField(max_length=20,help_text='Номер телефона') is_staff = models.BooleanField(default=True) # must needed, otherwise you won't be at is_active = models.BooleanField(default=True) # must needed, otherwise you won't be « is_superuser = models.BooleanField(default=False) # this field we inherit from Permis class Case(models.Model): CATEGORIES = [ ('Медицина','Медицина'),('Программирование','Программирование'), ('Архитектура','Архитектура') ] title = models.CharField(max_length=200,verbose_name='Название') description = models.TextField(verbose_name='Описание кейса') date_of_create = models.DateTimeField(auto_now=True) date_of_edit = models.DateTimeField(auto_now_add=True) date_of_close = models.DateTimeField() category = models.CharField(max_length=100,choices=CATEGORIES) user_id = models.ForeignKey(User,on_delete=models.CASCADE) Форма forms.py Нужно ли в форму добавлять user_id или к нему нужно присвоить pk? class AddCaseForm(ModelForm): class Meta: model = Case fields = ['title', 'description', 'category', 'date_of_close'] Мой views.py def createcase(request): form = AddCaseForm() error = '' if request.method == 'POST': form = AddCaseForm(request.POST) if form.is_valid(): form.save() return redirect('ShowCase') else: error = 'Форма была неверной' data = { 'form': form, 'error': error } return render(request,'createcase.html',data) Страница html createcase.html Форма должна передавать данные в базу {% extends 'base.html' %} {% block content %} <h1>Форма создания кейса</h1> <form method="post"> {% csrf_token %} {{ form.title }} <br> {{ form.description }} <br> {{ form.category }} <br> {{ form.date_of_close }} <br> <span>{{error}}</span> <button type="submit">Добавить</button> </form> {% endblock %} Как нужно правильно передать ключ и сохранить его в базу? -
Adapt my django view to form-wizard.init.js to save to database
I have a question, what happens is that I have a project in django that has the form-wizard.init.js and jquery.steps.min.js and it works quite well, I also placed a formset in django, all ok. The thing is that I just saw that for me to add to the database, my view does not work. Is there a way to save the data step by step with django and with those plugins? I also saw a way that is with django-formtools but if I implement it, what if I have already put form-wizard.init.js, it would be to put everything back from scratch. I will give an example of what I have in my code, not everything views.py def create_Presupuestos(request): extra_forms = 1 ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20) ManoObraFormSet = formset_factory(PresupuestosManoObraForm, extra=extra_forms, max_num=20) PagosFormSet = formset_factory(PresupuestosPagosForm, extra=extra_forms, max_num=20) presupuestosclientesform=PresupuestosClientesForm(request.POST or None) presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None) presupuestosparteform=PresupuestosParteForm(request.POST or None) presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None) presupuestospagosform=PresupuestosPagosForm(request.POST or None) presupuestosfotosform=PresupuestosFotosForm(request.POST or None) if request.method == 'POST': formset = ParteFormSet(request.POST, request.FILES) manoObra_formset = ManoObraFormSet(request.POST, request.FILES,prefix='manoobra') pagos_formset = PagosFormSet(request.POST, request.FILES, prefix='pagos') #formset = ParteFormSet(request.POST, request.FILES,prefix='__form') if formset.is_valid() and manoObra_formset.is_valid() and pagos_formset.is_valid(): presupuestosclientesform.save() return redirect('presupuestos:index') else: formset = ParteFormSet() manoObra_formset = ManoObraFormSet(prefix='manoobra') pagos_formset = PagosFormSet(prefix='pagos') presupuestosfotosform = PresupuestosFotosForm(request.POST or None) return … -
TypeError at /oauth/complete/mediawiki/ when upgrading to social-auth-app-django 3.3.0
I'm running: Python 3.7.3 Django 3.1.14 social-auth-app-django 3.1.0 When I try to upgrade social-auth-app-django to 3.3.0 or 3.4.0, I get: Traceback (most recent call last): File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_django/utils.py", line 49, in wrapper return func(request, backend, *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_django/views.py", line 33, in complete *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/actions.py", line 45, in do_complete user = backend.complete(user=user, *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/backends/base.py", line 40, in complete return self.auth_complete(*args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/utils.py", line 247, in wrapper return func(*args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/backends/oauth.py", line 181, in auth_complete return self.do_auth(access_token, *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/utils.py", line 247, in wrapper return func(*args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/backends/oauth.py", line 192, in do_auth return self.strategy.authenticate(*args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_django/strategy.py", line 107, in authenticate return authenticate(*args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/contrib/auth/__init__.py", line 73, in authenticate user = backend.authenticate(request, **credentials) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/backends/base.py", line 80, in authenticate return self.pipeline(pipeline, *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/backends/base.py", line 83, in pipeline out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/backends/base.py", line 113, in run_pipeline result = func(*args, **out) or {} File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/pipeline/user.py", line 119, in user_details … -
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 …