Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use List field in django models
I am maintaining a simple table with three columns: Course name, register and delete. Following is the screenshot of the table. Currently, when I click on register, I am changing the color of that row to dark and then changing register to unregister. template html file: Fist I get a text input i.e the course name <form class="form-inline my-2 my-lg-0" method="POST"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" placeholder="Add Item" aria-label="Search" name="item"> <button class="btn btn-outline-secondary my-2 my-sm-0" type="submit">Add to List</button> </form> Then I display the table {% if all_items %} <table class="table table-bordered"> {% for things in all_items %} {% if things.completed %} <tr class="table-secondary"> <td><a href="{% url 'edit' things.id %}">{{ things.item}}</a></td> <td><center><a href="{% url 'unregister' things.id %}">unregister</a></center></td> <td><center><a href="{% url 'delete' things.id %}">Delete</a></center></td> </tr> {% else %} <tr> <td><a href="{% url 'edit' things.id %}">{{ things.item}}</a></td> <td><center><a href="{% url 'register' things.id %}">register</a></center></td> <td><center><a href="{% url 'delete' things.id %}">Delete</a></center></td> </tr> {% endif %} {% endfor %} </table> {% endif %} views.py: from django.shortcuts import render,redirect from .models import List from .forms import ListForm def Link2(request): if request.method=='POST': form=ListForm(request.POST or None) if form.is_valid(): form.save() all_items=List.objects.all return render(request, 'Link2.html', {'all_items':all_items}) else: all_items=List.objects.all return render(request, 'Link2.html', {'all_items':all_items}) def register(request,list_id): item=List.objects.get(pk=list_id) item.completed=True item.save() return redirect('Link2') … -
Django server does not run properly when launched using os.startfile()
i've created a django server and created a shortcut that navigates through the initial setup it works perfectly when i run it normally by double clicking, but not when i launch it using python i created a function in tkinter that gets invoked when the button is clicked under which: os.startfile ("C:\server.lnk") command is given. when i click the button initial the server boots up, but navigated to a page show this error: enter image description here -
Django Tempus Dominus TimePicker does not return the instance of time when updating an object
I have a model, a form and a couple of views to add a new object and to update an object. Sending the form when adding works perfectly, and when I try to update an object (using an instance and the same form) the correct input for date shows, but time shows no input and I see warnings in the console about it, can anyone help me make sense of it? I feel like I've tried everything, this is my first time trying date and time pickers. I've simplified what I mean below. model.py: from django.db import models class MyModel(models.Model): date = models.DateField() time = models.TimeField() forms.py: from django import forms from .models import MyModel from tempus_dominus.widgets import DatePicker, TimePicker class MyModelForm(forms.ModelForm): date = forms.DateField(label="Start date", input_formats=['%d/%m/%Y'], widget=DatePicker(options={'format': 'DD/MM/YYYY', }, attrs={'autocomplete': 'off'})) time = forms.TimeField(label="Time (24 hour)",input_formats=['%H:%M'], widget=TimePicker(options={'format': 'HH:mm'}, attrs={'autocomplete': 'off'})) class Meta: model = MyModel fields = ('date', 'time') views.py def create_object_view(request): """View that creates a model entry""" if request.method == 'POST': object_form = MyModelForm(request.POST) if object_form.is_valid(): object_form.save() return redirect('wherever') else: object_form = MyModelForm) return render(request, 'create_object.html', {'object_form': object_form}) def update_object_view(request, object_id): """View that updates instance of model entry""" object = get_object_or_404(MyModel, pk=object_id) if request.method == 'POST': update_object_form = … -
How can I fix User and Models issue?
I am creating a project and I have 2 issues. In models.py I have: from django.db import models from children.models import Child from django.contrib.auth.models import User class OrderLineItem(models.Model): order= models.ForeignKey("Order", null=False, on_delete=models.CASCADE, related_name="order") child = models.ForeignKey(Child, null=False, on_delete=models.CASCADE) donation = models.IntegerField(blank=False) def __str__(self): return "{0}-{1}".format( self.donation, self.child.name) class Order(models.Model): full_name = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) phone_number = models.CharField(max_length=20, blank=False) country = models.CharField(max_length=40, blank=False) postcode = models.CharField(max_length=20, blank=True) town_or_city = models.CharField(max_length=40, blank=False) street_address1 = models.CharField(max_length=40, blank=False) street_address2 = models.CharField(max_length=40, blank=True) date = models.DateField() orderlineitem = models.ForeignKey(OrderLineItem, on_delete=models.CASCADE, related_name="orderlineitem") def __str__(self): return "{0}-{1}-{2}".format(self.id, self.date, self.full_name) In the html I have: {% if orders %} <h3>Your donations history: </h3> {% for order in orders %} <div class="history"> <h4>Order number: {{order.id}}</h4> <ul class="history-list"> <li scope="row">Date of your order: {{ order.date }}</li> <li scope="row">Child: {{ order.child }}</li> <li scope="row">Donation: {{ order.donation }} €</li> </ul> </div> {% endfor %} {% else %} <h3>You have not made any donations yet. </h3> {% endif %} And I get an error: Traceback: File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) File "/usr/local/lib/python3.6/dist-packages/django/db/backends/sqlite3/base.py" in execute 328. return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: checkout_order.orderlineitem_id) was the direct cause of the following exception: File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner 41. … -
Nginx - how to serve protected video on a rendered page in Django, instead of a forced download?
I need a protected video file on a page rendered by Django. The file is protected, but it's not serving an html rendered page with the <video src="..."> as I'd expect, like netflix. Instead, all I get is a jumbled mess like this image. I know the internal redirect is serving the file, therefore it shows up like that, but I need it on a rendered page with the other html like netflix does.... What am I doing wrong?? Nginx conf file: location /secret_videos/ { internal; alias /home/username/path/to/secret/videos/; } Url: path('protected_video/', views.protected_video, name='protected_video'), View: def protected_video(request): .... if request.method =='POST': if some_var == 'the_correct_value': protected_uri = '/secret_videos/secret-vid-1.mp4' response = render(request, 'template.html', {'some_var ': True, 'protected_uri': protected_uri}) response['X-Accel-Redirect'] = protected_uri return response return render(request, 'template.html', {}) Template, but it's not rendering html, only the image above: <video width="75%" height="auto" controls> <source src="{{ protected_uri }}" type="video/mp4" /> Your browser doesn't support the mp4 video format. </video> -
Link To Config File And Use That Info To Link To Another Config File In Django View
I was wondering if it was possible to link to two config files at the same time in a django view (context)? So I have my main config.py file in my main app folder and another one is stored at themes/default/config.py to store info for that theme so I want to call that configs "THEME_PATH" and use that to link to the themes config.py file to use in the template. main config.py: SITE_NAME = 'Site Title' THEME_PATH = 'themes/' SITE_THEME = 'default' themes/default/config.py: # Homepage HOMEPAGE_TITLE = 'Home' HOMEPAGE_DESCRIPION = 'Welcome to our site!' HOMEPAGE_KEYWORDS = '' # Forums FORUM_TITLE = 'Forums' FORUM_HEADER_TITLE = 'Welcome To Our Site' FORUM_HEADER_TEXT = 'Welcome to the forums a place to talk about anything.' FORUM_DESCRIPION = 'This is our forum' FORUM_KEYWORDS = '' views: from django.shortcuts import render, import app.config def forums_home_view(request): # ... context = { 'site_name': app.config.SITE_NAME, 'forum_title': app.config.THEME_PATH.SITE_THEME.config.FORUM_TITLE, 'forum_description': app.config.THEME_PATH.SITE_THEME.FORUM_DESCRIPION, 'forum_header_text': app.config.THEME_PATH.SITE_THEME.FORUM_HEADER_TEXT, 'forum_keywords': app.config.THEME_PATH.SITE_THEME.FORUM_KEYWORDS, } return render(request, f"{app.config.SITE_THEME}/forum_home.html", context) I tried doing it like app.config.THEME_PATH.SITE_THEME but that didn't work also tried a few others way and also didn't work so any help will be great -
Django: No module named 'psycopg2' when launching migrations to heroku
I am new to django and I created a website and now I am in the deployment phase, all is well run until launching migrating from the database to the server. I'll show you everything I've done since the beginning structure of my project OC_project8/ pur_beurre/ catalog/ dumps/ catalog.json ... # other classic file media/ pur_beurre/ static/ .gitignore ... # other classic file static/ templates/ users/ manage.py Procfile venv/ requirements.txt/ .gitignore/ All command was run in a virtual environement, for exemple: (venv) ~/OC_project8/pur_beurre$ sudo apt-get install python-psycopg2 I did all the necessary steps before runing the command git push heroku master (git commit, heroku create my-app ...) if you need more detail on these steps tell me. After runing the command git push heroku master I had this error: .... remote: Collecting pkg-resources==0.0.0 (from -r /tmp/build_cac68f54540915062647a425c52dc61b/requirements.txt (line 11)) remote: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r/tmp/build_cac68f54540915062647a425c52dc61b/requirements.txt (line 11)) (from versions: ) remote: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_cac68f54540915062647a425c52dc61b/requirements.txt (line 11)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to pur-beurre-oc8. remote: To https://git.heroku.com/pur-beurre-oc8.git ! [remote rejected] master -> … -
Saving ManytoMany fields in Django with multiple forms
I am trying to do the following in 3 forms that are processed at once: 1. Save the subject line for an email (this works) 2. Save the email content. (this works) 3. Save the email title (works) and save the relationship to the subject line and to the email content (not working). I have read through every page I could which had to do with errors. I have tried it a variety of different ways, but they all haven't worked for me. View.py: def email_subject_create_view(request): if request.method == 'POST': email_subject_form = EmailSubjectForm(request.POST) email_content_form = EmailContentForm(request.POST) email_form = EmailForm(request.POST) if email_subject_form.is_valid() and email_content_form.is_valid() and email_form.is_valid() : subject = email_subject_form.save(commit=False) subject.time_created = datetime.datetime.now() contractor = Contractor.objects.get(user_id=request.user.id) subject.save() email_subject_form.save_m2m() content = email_content_form.save(commit=False) content.time_created = datetime.datetime.now() content.save() email_content_form.save_m2m() email = email_form.save(commit=False) email.time_created = datetime.datetime.now() correct_subject = EmailSubject.objects.get(pk=subject.id) # this is what I want to do. email.email_core_contents is a M2M field email.email_core_contents = subject.id email.save() context = { 'email_subject_form': EmailSubjectForm(), 'email_content_form': EmailContentForm(), 'email_form': EmailForm(), } return render(request, 'advertise/email_subject_create.html', context) I have tried: email.email_core_contents = EmailSubject.objects.get(pk=subject.id) email.email_core_contents.set(subject) email.email_core_contents.set(pk=subject.id) I have also tried it without the .save_m2m() portions of code. -
Visual Studio Code switching terminals when debugging. Code only runs successfully once with debugger
I am trying to debug Django code with Visual Studio Code on windows 10. When I run the debugger for the first time, my code compiles successfully and nothing goes wrong. If I change something in the code, and rerun the debugger I get a giant slew of commands on my Python Debug console run into the same error report I ran into before (from the first run even with new code without any user interaction on my webapp). Some notes: It seems very consistent. If I close visual studio code and rerun it-- my code runs fine... for one run. Closing the python debug console, it reruns fine on my default terminal--powershell. -
My page doesn't redirect when I click, but my other buttons work?
I have a page that contains a form. It has 3 buttons, Enter/Leave and Options. My enter and leave button operate just fine, but the options button is supposed to redirect to a list of entries and currently it does not do anything, not even produce errors, which I can't figure out why it's happening. views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['adp_number'] if 'enter_area' in self.request.POST: form.save() return HttpResponseRedirect(self.request.path_info) elif 'leave_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter(adp_number=emp_num).update(time_out=datetime.now()) return HttpResponseRedirect(self.request.path_info) elif 'manager_options' in self.request.POST: return redirect('enter_exit_area_manager_options_list') class EnterExitAreaManagerOptionsList(ListView): filter_form_class = EnterExitAreaManagerOptionsFilterForm default_sort = "name" template = "operations/list.html" def get_initial_queryset(self): return EmployeeWorkAreaLog.active.all() def set_columns(self): self.add_column(name='Employee #', field='adp_number') self.add_column(name='Work Area', field='work_area') self.add_column(name='Station', field='station_number') urls.py urlpatterns = [ url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'), url(r'enter-exit-area-manager-options-list/$', EnterExitAreaManagerOptionsList.as_view(), name='enter_exit_area_manager_options_list'), ] enter_exit_area.html {% extends "base.html" %} {% block main %} <form id="warehouseForm" action="" method="POST" novalidate > {% csrf_token %} <div> <div> {{ form.adp_number.help_text }} {{ form.adp_number }} </div> <div> {{ form.work_area.help_text }} {{ form.work_area }} </div> <div> {{ form.station_number.help_text }} {{ form.station_number }} </div> </div> <div> <div> <button type="submit" name="enter_area" value="Enter">Enter Area</button> <button type="submit" name="leave_area" value="Leave">Leave Area</button> </div> </div> </form> {% endblock main %} {% block panel_footer %} <div class="text-center"> <button … -
Make a certain form field read only when passing form to the template in Django 2
I have a form where I am passing the initial value of username and email. According to my logic I need these fields to turn into read only. Is there any way to do this using the forms in the view function. models.py class Profile(models.Model): STATUS_CHOICES = ( (1, ("Permanent")), (2, ("Temporary")), (3, ("Contractor")), (4, ("Intern")) ) GENDER_CHOICES = ( (1, ("Male")), (2, ("Female")), (3, ("Not Specified")) ) PAY_CHOICES = ( (1, ("Fixed")), (2, ("Performance Based")), (3, ("Not Assigned")), ) user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) emp_type = models.IntegerField(choices=STATUS_CHOICES, default=1) start_date = models.DateField(default=timezone.now) end_date = models.DateField(null=True, blank=True) user_active = models.BooleanField(default=True) contact = models.CharField(max_length=13, blank=True) whatsapp = models.CharField(max_length=13, blank=True) gender = models.IntegerField(choices=GENDER_CHOICES, default=3) pay_type = models.IntegerField(choices=PAY_CHOICES, default=3) pay = models.IntegerField(default=0) avatar = models.ImageField(upload_to='users/images', default='users/images/default.jpg') title = models.CharField(max_length=25, null=True, blank=True) #manager_username = models.ForeignKey(User, blank=True, null=True, to_field='username',related_name='manager_username', on_delete=models.DO_NOTHING) def __str__(self): return self.user.username forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(required=True, label='Email', error_messages={'exists': 'Oops'}) class Meta: model = User fields = ("username", "first_name", "email", "password1", "password2") class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['pay_type', 'emp_type', 'contact', 'whatsapp', 'gender', 'avatar'] views.py def nda(request): context = {} if request.method=='POST' and request.session['email']: email = request.session['email'] username = request.session['username'] position_name = request.session['position_name'] name = request.session['name'] pay_type = request.session['pay_type'] emp_type … -
How do I redirect a webhook to a Django channels consumer?
I am basically trying to use Twilio's SMS webhooks to redirect a text message to a Django Channels consumer. The idea is to have a person be able to send a text to a number, the number redirects the text (through Twilio webhooks) to appear in a chat room, have someone respond in the chat to the phone number (the responses would be texts sent out by Twilio as well). So far I have followed the Django Channels tutorial here: https://channels.readthedocs.io/en/latest/tutorial/index.html I have gotten up to step 4, however I don't need to worry about testing right now. The chat program currently works. When I try to send a text via Twilio, and I check the debugger on Twilio, it gives me a 403 error (Forbidden Error). I tried using the crsf_exempt token on the class and the connect function, however this error continues to occur when I send a text. I can't provide code because the code is proprietary, however it is very similar to the code in the tutorial in the link above. I am hoping to have the Consumer "connect" method run (connecting to the websocket), followed by a text message being received by the consumer, then … -
Why the Django redirects url to undesired page
I try to make user registration in Django (version 2.2). I can run local server and fill register form in but when I click on submit button then there is diffrent redirecting and new user is not created. Instead of redirecting to main page ('/') there is redirecting to 'accounts/register/register' and I don't know why. Can somebody help me to find the problem. Earlier in views.py I used import User from django.contrib.auth.models and changed the code in register.html but the problem was the same. Maybe something is wrong with my settings.py? in settings.py I added to INSTALLED_APPS = ['users.apps.UsersConfig',] and at the end LOGIN_REDIRECT_URL = '/' # views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.forms import UserCreationForm def register(request): if request.method == "POST": form_register = UserCreationForm(request.POST) if form_register.is_valid(): username = form_register.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('register/') else: form_register = UserCreationForm() return render(request, "registration/register.html", {'form_register': form_register}) # urls.py from django.contrib import admin from django.urls import path, include from users.views import register urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('accounts/register/', register),] # apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' # register.html <!doctype html> <html> <head> <title>Register</title> </head> <body> <form action="register" method="POST"> {% csrf_token … -
'Calculate' variables as fields in the Django model
I have a simple model: class Atividade(models.Model): valor_brl = models.DecimalField(max_digits=14, decimal_places=2) dolar_ref = models.DecimalField(max_digits=14, decimal_places=2) valor_usd = models.DecimalField(max_digits=14, decimal_places=2) I create after a method to calculate a new value using the two fields from the model @property def valor_usd_novo(self): valor_usd_novo = self.valor_brl / self.dolar_ref return valor_usd_novo If I call {{ valor_usd_novo }} I get the result I want. After this I create the save() method, to save valor_usd_novo result in valor_usd field from the model. def save(self, *args, **kwargs): self.valor_usd = self.valor_usd_novo() super(Atividade, self).save(*args, **kwargs) The point is that when I call valor_usd I got no results and the database do not update with the result from valor_usd_novo method. What I missing here? -
Does django-private-chat save chat history?
I'm working on a django project in which I need to implement one-to-one chat/message for users. I am thinking more like LinkedIn messaging. Here is an ideal situation. messages show up in a chat box a user can send message when the other user is offline messages are somehow saved. so when a user opens up the message box, all prior messages show up. a user can delete message history notification about unread messages (in the app, not by email) I did some search and found django-private-chat that seems can do 1, 2, but not the other ones. Question 1: django-private-chat seems not saving chat history. Am I right? If so, is there any way I can save the chat history? Question 2: Is there any other packages that I should take a look? Thanks. -
What is the proper way to continuously/lazy load data from Django into Angular
I am trying to create a blog where all the comments get loaded on each blog post page. The issue is that some posts can contain a few comments which takes seconds to load while others can contain well over 100 which will take a lot longer. I want to load each comment independently one after another to decrease waiting time so they can work seamlessly but I dont know if this is the best approach. Assuming I cant use pagination(I need it as one continuously list), what would be the best method/approach? -
How to fix this simple issue?
when i type python manage.py runserver on windows powershell , the django server is working properly but when i tried to run the django server on pycharm, server not connecting and give this error Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? . How do i fix this error? -
Django rest self-referencing ForeignKey error Direct assignment to the reverse side of a related set is prohibited. Use parent.set() instead
Model: class Comment(models.Model, CharField, ListField): user = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='comment_user', blank=True, null=True) news = models.ForeignKey(News, related_name='comment_of', on_delete=models.CASCADE) content = models.CharField(validators=[MinLengthValidator(4)], max_length=200") parent_comment = models.ForeignKey('self', blank=True, null=True, related_name='parent', on_delete=models.CASCADE) class Meta: ordering = ['-created'] def __str__(self): return self.content When I login in admin click comment,there is an error: Direct assignment to the reverse side of a related set is prohibited. Use parent.set() instead. When I remove: parent_comment = models.ForeignKey('self', blank=True, null=True, related_name='parent', on_delete=models.CASCADE) The error gone. So,how to modify parent_comment,I think the issue is here. -
Django check if form input field is not empty
I have a form that has a bunch of fields. These are all the fields for product checkout. So name, last name, email, adress, phone and more. Then there is a button type submit that proceeds to the next page. What i want to do, is if any of these fields are empty, there should be a red text saying: "field is empty" otherwise it would proceed. This is how i tried to do it: <form class="row contact_form" action="{% url 'create-order' %}" method="POST" novalidate="novalidate"> {% csrf_token %} <div class="col-md-6 form-group"> <input type="text" class="form-control" name="order-namn" placeholder="Namn"> </div> <div class="col-md-6 form-group"> <input type="text" class="form-control" name="order-efternamn" placeholder="Efternamn"> </div> <div class="col-md-12 form-group"> <input type="text" class="form-control" name="order-epost" placeholder="E-post för orderbekräftelse"> </div> <div class="col-md-6 form-group"> <input type="text" class="form-control" name="order-adress" placeholder="Adress"> </div> <div class="col-md-6 form-group"> <input type="text" class="form-control" name="order-ort" placeholder="Ort"> </div> <div class="col-md-6 form-group"> <input type="text" class="form-control" name="order-postnummer" placeholder="Postnummer"> </div> <div class="col-md-6 form-group"> <input type="text" class="form-control" name="order-telefon" placeholder="Telefon"> </div> <div class="col-md-2 form-group"> <select class="browser-default" name="order-land"> <option value="Sverige" selected>Sverige</option> </select> </div> <div class="col-md-2 form-group p_star"> <select class="browser-default" name="order-state"> <option selected>Län</option> <option value="Blekinge län">Blekinge län</option> <option value="Dalarnas län">Dalarnas län</option> <option value="Gotlands län">Gotlands län</option> <option value="Gävleborgs län">Gävleborgs län</option> <option value="Hallands län">Hallands län</option> <option value="Jämntlands län">Jämntlands län</option> <option value="Jönköpings län">Jönköpings län</option> … -
How to query serialized queryset
I have a fairly static table that does not get updated too often. I have decided to cut down on database hits by caching the queryset in redis by serializing it as json. Is there a way for me to convert the data in some way where I can query it similar to a Django queryset? old way mymodel.objects.get(fname="foo", lname="bar") new way I want to do cached_qs = REDIS_CACHE.get('key') cached_qs.get(fname="foo", lname="bar") I am storing them in redis as a json serialized string REDIS_CACHE.set('key', serializers.serialize('json', Currency.objects.all())) -
How to localize a date field in a django generic view
I am very new to Python and Django and started to learn it just recently. So, I wanted to create a form with Django using generic views, here CreateView. In my form I have a date field and this only works with entries like "01/01/1970". But for my settings I need the validation to understand "01.01.1970" to be the same date (so, basically %D.%M.%Y or something similar). I found instructions how to use this with a self built form, but I do not understand how to use parameters like "localize=True" in combination with a generic view yet. Because I do not have a template which lists all of the fields separately. This is done automatically by a loop, if I understood that correctly. -
How to iterate over Django model fields, and add values based on a condition
I have a model that simulates a train line with up to 30 stations, so the model has 30 nullable fields. models.py class TempLine(models.Model): picking_mode = models.IntegerField(default=1) start_station = models.CharField(max_length=2000) end_station = models.CharField(max_length=2000, null=True) station_1 = models.CharField(max_length=2000, null=True) station_2 = models.CharField(max_length=2000, null=True) station_3 = models.CharField(max_length=2000, null=True) station_4 = models.CharField(max_length=2000, null=True) station_5 = models.CharField(max_length=2000, null=True) station_6 = models.CharField(max_length=2000, null=True) station_7 = models.CharField(max_length=2000, null=True) station_8 = models.CharField(max_length=2000, null=True) station_9 = models.CharField(max_length=2000, null=True) station_10 = models.CharField(max_length=2000, null=True) station_11 = models.CharField(max_length=2000, null=True) station_12 = models.CharField(max_length=2000, null=True) station_13 = models.CharField(max_length=2000, null=True) station_14 = models.CharField(max_length=2000, null=True) station_15 = models.CharField(max_length=2000, null=True) station_16 = models.CharField(max_length=2000, null=True) station_17 = models.CharField(max_length=2000, null=True) station_18 = models.CharField(max_length=2000, null=True) station_19 = models.CharField(max_length=2000, null=True) station_21 = models.CharField(max_length=2000, null=True) station_22 = models.CharField(max_length=2000, null=True) station_23 = models.CharField(max_length=2000, null=True) station_24 = models.CharField(max_length=2000, null=True) station_25 = models.CharField(max_length=2000, null=True) station_26 = models.CharField(max_length=2000, null=True) station_27 = models.CharField(max_length=2000, null=True) station_28 = models.CharField(max_length=2000, null=True) station_29 = models.CharField(max_length=2000, null=True) station_30 = models.CharField(max_length=2000, null=True) The data is being added one by one using ajax request. so I have to loop through all the fields starting from station_1 ..checking if it is none, add .. if not .. just go for next one. here is how I tried to do it: def adding_inline_stations(request): in_line_station = … -
'register' object has no attribute 'get' in Django
Hi Everyone i make a blog with django but i need to register use and always i get this error: AttributeError at /register/ 'register' object has no attribute 'get' i already search too many times but i don't get correct answer so make sure don't mark as a duplicate Here is my Views.py from django.shortcuts import render , get_object_or_404,redirect from django.utils import timezone from blog.models import * from blog.forms import * from django.contrib.auth.decorators import login_required from django.urls import reverse_lazy from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) # Create your views here.\ def user_register(request): if request.method == "POST": reg = register(data=request.POST) if reg.is_valid(): user = reg.save() user.set_password(user.password) user.save() else: print(register.errors) else: reg = register() return render(request,'register.html',{'reg':reg}) Here is my Models.py class register(models.Model): user = models.OneToOneField(User,on_delete="Cascade") Here is my Forms.py class register(forms.ModelForm): class Meta(): model = User fields = ('username','email','password') I'm Wating For Your Answers! -
how to add Paginator to search result in django?
hello i want add Paginator in search result page , so what i should add to my view.py ? my code : views.py : def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') # page = request.GET.get('page', 1) # the_home_page is the name of pages when user go to page 2 etc if query is not None: home_database= Homepage.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcprograms_database= PCprogram.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidapk_database= AndroidApks.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidgames_database= AndroidGames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) antiruvs_database= Antivirus.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) systems_database= OpratingSystems.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcgames_database= PCgames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) results= list(chain(home_database,pcprograms_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database)) context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/enterface.html', context) else: return render(request, 'html_file/enterface.html') else: return render(request, 'html_file/enterface.html') also what i should write in html file ? -
Update multiple rows in mysql table with single call
I have a table in MySql DB. I need to update a particular column for all the rows in the table. I need to do this in a single call without deleting the rows, only updating the column values. I have tried using df.to_sql(if_exists='replace') but this deletes the rows and re-inserts them. Doing so drops the rows from other table which are linked by the foreign key. merge_df = merge_df[['id', 'deal_name', 'fund', 'deal_value']] for index, row in merge_df.iterrows(): ma_deal_obj = MA_Deals.objects.get(id=row['id']) ma_deal_obj.deal_value = row['deal_value'] ma_deal_obj.save() merge_df has other columns as well. I only need to update the 'deal_value' column for all rows. One solution I have is by iterating over the dataframe rows and using Django ORM to save the value but this is quite slow for too many rows.