Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django: Using a for loop to view all images from my db - using img src
I am currently learning Django and making my first steps. I try to build a webgallery to learn all the basic stuff. I successfully displayed some images using static files. So I tried saving Images through ImageFields and "upload_to" in my DB, saving it to my static directory. I tried to display everyone of them with a for loop in an tag. My img displays properly with using a {% static %} tag but when I try to insert a {{ }} Tag it isn't working, although it's the same url it doesn't work. I tried changing my STATIC FILE in settings.py I tried various other forms of nesting my {{}} in there Reading the docs to staticfile https://docs.djangoproject.com/en/2.2/howto/static-files/ This thread Display an image located in the database in Django This thread https://docs.djangoproject.com/en/2.2/topics/files/#using-files-in-models My Code: <p>Overview</p> {% block content %} <div> {% for image in images %} {{ image.img_photo }} <!-- webgalleries/test.jpg --> {% load static %} <img src="{% static 'webgalleries/test.jpg' %}" alt="{{ image }}"> <!-- working --> <img src="{% static '{{ image.img_photo }}' %}" alt="{{ image }}"> <!-- not working --> {% empty %} <p>No content</p> {% endfor %} </div> {% endblock content %} I expect the output to … -
In Django does .get() have better performance than .first()?
The Django implementation of .first() seems to get all items into a list and then return the first one. Is .get() more performant ? Surely the database can just return one item, the implementation of .first() seems suboptimal, -
How to pass two arguments between two views in Django?
I am converting a Flask project into Django one. I have a view1 function that takes user input and passes it to a function1 that returns two variables. Variable x is used in query string and passed to view2. However, I also need to pass variable y to view2 for further operations. I Flask application I used expression 'global y' but this does not work in Django. Any ideas, def function1(input): #does something return x,y def view1(request): form = SomeForm() context={'form': form} if request.method == "POST": form = SomeForm(request.POST) if form.is_valid(): input = form.cleaned_data['data_from_user'] # global y --> works only in Flask x,y = function1(input) return redirect("view2", x) # goes to path('<str:x>/', views.my_app, name='view2') return render(request, "my_app/view1.html", context) def view2(request, x): record = SomeTable.objects.filter(y=y).first() context = {'record': record} return render(request, "my_app/view2.html", context) -
Error connecting Google AppEngine Django with SQL 2nd generation instance?
I want migrating my site from First to Second Generation SQL instance, this is the old config: DATABASES['unidades'] = { 'ENGINE': 'google.appengine.ext.django.backends.rdbms', 'INSTANCE': 'tcontur2:posiciones', 'NAME': 'unidades', 'USER': MY_USER, 'PASSWORD': 'MY_PASSWORD', } This works fine, now I trying with this code: DATABASES['unidades'] = { # 2da gen no funciono error COUNT_ROWS 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/tcontur2:us-central1:second-gen-1572540648416', 'NAME': 'unidades', 'USER': MY_USER, 'PASSWORD': MY_PASSWORD } And this code DATABASES['unidades'] = { # 2da gen no funciono error COUNT_ROWS 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/tcontur2:us-central1:second-gen-1572540648416', 'NAME': 'unidades', 'USER': MY_USER, 'PASSWORD': MY_PASSWORD } And this is the error: AttributeError at / 'module' object has no attribute 'FOUND_ROWS' ... /base/alloc/tmpfs/dynamic_runtimes/python27g/79cfdbb680326abd/python27/python27_lib/versions/third_party/django-1.5/django/db/models/query.py in _result_iter self._fill_cache() ... ▶ Local vars /base/alloc/tmpfs/dynamic_runtimes/python27g/79cfdbb680326abd/python27/python27_lib/versions/third_party/django-1.5/django/db/models/query.py in _fill_cache self._result_cache.append(next(self._iter)) ... ▶ Local vars /base/alloc/tmpfs/dynamic_runtimes/python27g/79cfdbb680326abd/python27/python27_lib/versions/third_party/django-1.5/django/db/models/query.py in iterator for row in compiler.results_iter(): ... ▶ Local vars /base/alloc/tmpfs/dynamic_runtimes/python27g/79cfdbb680326abd/python27/python27_lib/versions/third_party/django-1.5/django/db/models/sql/compiler.py in results_iter for rows in self.execute_sql(MULTI): ... ▶ Local vars /base/alloc/tmpfs/dynamic_runtimes/python27g/79cfdbb680326abd/python27/python27_lib/versions/third_party/django-1.5/django/db/models/sql/compiler.py in execute_sql cursor = self.connection.cursor() ... ▼ Local vars Variable Value self <django.db.backends.mysql.compiler.SQLCompiler object at 0x3e7ec68e0890> params (1,) result_type 'multi' sql u'SELECT `posicion_unidades`.`id`, `posicion_unidades`.`empresa`, `posicion_unidades`.`ruta`, `posicion_unidades`.`lado`, `posicion_unidades`.`padron`, `posicion_unidades`.`placa`, `posicion_unidades`.`longitud`, `posicion_unidades`.`latitud`, `posicion_unidades`.`hora`, `posicion_unidades`.`velocidad`, `posicion_unidades`.`direccion`, `posicion_unidades`.`metros`, `posicion_unidades`.`color`, `posicion_unidades`.`frecuencia`, `posicion_unidades`.`estado`, `posicion_unidades`.`ultima`, `posicion_unidades`.`actual`, `posicion_unidades`.`sin_boletaje`, `posicion_unidades`.`con_boletaje`, `posicion_unidades`.`record`, `posicion_unidades`.`volada`, `posicion_unidades`.`control`, `posicion_unidades`.`datero`, `posicion_unidades`.`log`, `posicion_unidades`.`odometro`, `posicion_unidades`.`datero_atras`, `posicion_unidades`.`llamada`, `posicion_unidades`.`emergencia`, `posicion_unidades`.`salio`, `posicion_unidades`.`conectado`, `posicion_unidades`.`fuera`, `posicion_unidades`.`correteo`, `posicion_unidades`.`antena`, `posicion_unidades`.`exceso_velocidad`, `posicion_unidades`.`limite`, `posicion_unidades`.`activo`, `posicion_unidades`.`chofer`, `posicion_unidades`.`ticket` FROM … -
How can I fix a Django ForeignKey error: (adming E202)?
I am creating a project. 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): child = models.ForeignKey(Child, null=False, on_delete=models.CASCADE, related_name="child") 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) def __str__(self): return "{0}-{1}-{2}".format(self.id, self.date, self.full_name) However, in the console I get: ERRORS: class 'checkout.admin.OrderLineAdminInline': (admin.E202) 'checkout.OrderLineItem' has no ForeignKey to 'checkout.Order'. How can I fix this? -
Django REST Framework Authentication keyword
I'm trying to rename the Rest_framework TokenAuthentication keyword from "Token" to "Bearer" as suggested in the Documentation I have subclassed the TokenAuthentication class like this: in module: user/authentication.py from rest_framework import authentication class TokenAuthentication(authentication.TokenAuthentication): """ Simple token based authentication. Clients should authenticate by passing the token key in the "Authorization" HTTP header, prepended with the string "Token ". For example: Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a """ keyword = 'Bearer' in module app/settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'user.authentication.TokenAuthentication', ), } It is still sending me a 401 Unauthorized when im using 'Authorization: Bearer ...token...' but not with 'Authorization: Token ...token...' What am I doing wrong ? -
How to properly execute this ajax request with Django?
I made a page with form that has a few fields from a model called EmployeeWorkAreaLog, the first field being where a person enters their Employee #, which is tied to a separate model called Salesman that has all the main data for verification. I made this function get_employee_name(), which returns the name based on the Employee # from the other model, but I'm not sure how to display it in the page, right on the top, without refreshing after the person tabs/clicks out into the next field in the form? I'm not too familiar with html, but I was reading an ajax request would do the trick, but I'm not sure how to approach this. Below you can see what I attempted, but I'm not sure how to handle the success or how to properly insert it into the html. This is basically so the person knows that the Employee # they entered matches their name before proceeding to fill the rest out. 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'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_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() … -
django two m2m models
I am quite new to databases as such, and I am trying to figure out how to set up an M2M model with 2 models. So, I have gone through the official docs for m2m and it is pretty clear for the example with Publications and Article`. I completely get it. However, in my use case, I unfortunately have a three way relationship between 3 models like so: Teacher has many students students can have many teachers students can attend many schools Teacher can teach in many schools Where Teachers, Students and Schools are three different models. How does one set up such a model using m2m in django? -
How can to start tasks with celery-beat?
Why i can't run a periodic tasks? proj/settings.py REDIS_HOST = 'localhost' REDIS_PORT = '6379' CELERY_BROKER_URL = 'redis://localhost:6379' BROKER_URL = 'redis://' + REDIS_HOST + ':' + REDIS_PORT CELERY_BEAT_SCHEDULE = { 'task-first': { 'task': 'app.tasks.one', 'schedule': timedelta(seconds=1) }, 'task-second': { 'task': 'app.tasks.two', 'schedule': crontab(minute=0, hour='*/3,10-19') } } proj/celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) proj/__init.py__ from .celery import app as celery_app __all__ = ['celery_app'] celery -A proj worker -l info [2019-10-31 16:57:57,906: INFO/MainProcess] Connected to redis://localhost:6379// [2019-10-31 16:57:57,912: INFO/MainProcess] mingle: searching for neighbors [2019-10-31 16:57:58,927: INFO/MainProcess] mingle: all alone [2019-10-31 16:57:58,951: INFO/MainProcess] celery@lexvel-MS-7A72 ready. Tasks are found celery -A oddsportal beat -l info Configuration -> . broker -> redis://localhost:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2019-10-31 16:58:02,851: INFO/MainProcess] beat: Starting... The celerybeat.pid and celerybeat-shedule files are created. But besides these lines nothing more is displayed.