Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i cannot login to the page
iam trying to create a login page for users whom i have created using django admin can login. But by the below code i cannot login i.e after clicking login button im not being redirected to the page i have given. forms1.py from django import forms class UserForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'})) password = forms.CharField(widget=forms.PasswordInput(attrs= {'placeholder': 'Password'})) fields = ['username', 'password'] views.py def Userform(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): userObj = form.cleaned_data username = userObj['username'] password = userObj['password'] user = authenticate(Username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect('/user/') else: form = UserForm() return render(request, 'index.html', {'form' : form}) urls urlpatterns = [ path('admin/', admin.site.urls), path('user/',user), path('login/',Userform), ] index.html <form class="login-form" method="post" action=""> {% csrf_token %} {{ form.as_p }} <button type="submit">login</button> </form> -
Creating a Staff Tracker Webapp - initial ideas
I am starting a new project where I am building a staff tracker tool that keeps track of where employees are when they are at a client or bench. I will be using Django as my framework and Postgresql as my database. I have some experience with coding using Django building a search tool but not with calendars. This is the first design we have: How to implement a calendar like that When a date is chosen(clicked), two drop down lists appear to select "Client" and "Location" How to implement a range of dates so i can do a bulk update e.g. start: 01/01/2019 end: 01/05/2019, and whatever client and location has been selected would be saved across those dates -
Annotate a LineString onto a GeoDjango queryset
For a given user, I'm trying to find out the other users who drive closest to them. For carpooling. Here are my abbriviated models: class Office(models.Model): location = PointField(srid=4326, geography=True) class User(models.Model): office = fk(Office) home_location = PointField(srid=4326, geography=True) In my head, I need to do a few things: Annotate on a LineStringField of F('home_location')→F('office__location') to represent an as-the-crow-flies route to work. Annotate on the shortest distance for each route from the given user's home_location. Sort by that distance, desc. It looks simple on paper but I'm stumbling at the first hurdle. How do I annotate on a LineStringField? This seems like it would be a very common problem for anybody using GIS in Django. -
insert data from a post request to a database in django
I created an application in django that gets a questions from a table Survey_body and render them in a modal form in html file , and on submit it sends a POST request . But when I pass the data to the Answer table which have 3 fields :Q_id,answer and browser_name , it pass the value of Q_id but not the other two fields (answer and browser_name). Can any one help me to solve this problem . models.py class Survey_body(models.Model): ANSWER_TYPES = ( ('S', 'Stars'), ('E', 'Emoji'), ('N', 'Numbers'), ('T','Text'), ) survey_id= models.ForeignKey(Survey,on_delete=models.CASCADE) q_id= models.PositiveIntegerField(primary_key=True) quistion= models.CharField(max_length=500) answer_type= models.CharField(max_length=50,choices= ANSWER_TYPES,default= "") def __str__(self): return str(self.survey_id) + ' ==> body_id=' + str(self.q_id) +" the question is: " +self.quistion class Answer(models.Model): q_id= models.ForeignKey(Survey_body, on_delete= models.CASCADE, default=1) answer= models.CharField(max_length=2000) browser_name = models.TextField(blank=True) def __str__(self): return str(self.q_id) + " answer is: " + str(self.answer) views.py def PostToAnswer(request): q2= Survey.objects.filter(survey_id__exact=1).get() q= Survey_body.objects.filter(survey_id__exact=1).all() #to get all records in Survey_bodey if request.method == 'POST': for item in q: if(request.POST.get(item.quistion)): r_o= sn.get(item.quistion) Answer().q_id= item Answer().answer= sn.get(item.quistion) Answer().browser_name= request.user_agent.browser.family Answer().save() else: print('else') return redirect("modal") return render(request,"base2.html") def modal(request): a= Answer() q2= Survey.objects.filter(survey_id__exact=1).get() q= Survey_body.objects.filter(survey_id__exact=1).all() #to get all records in Survey_bodey context={ 'question': q, 'survey': q2, } return render(request,"modal.html",context) modal.html … -
How to redirect Django admin custom button to a view
I have made a Django custom button: {% extends 'admin/change_form.html' %} {% block submit_buttons_bottom %} {{ block.super }} <div class="submit-row"> <input type="submit" value="Make Unique" name="_make-unique"> </div> {% endblock %} Then I want to link this button to a view: something like this: <input type="submit" value="Make Unique" name="_make-unique" onclick="location.href="{% url '/response_change' %}> this is my url.py: urlpatterns = [ url(r'^admin/', admin.site.urls), path('admin/response_change/', views.response_change, name='response_change'), ] and the view.py: def response_change(self, request, obj): if "_make-unique" in request.POST: matching_names_except_this = self.get_queryset(request).filter(name=obj. ˓→name).exclude(pk=obj.id) matching_names_except_this.delete() obj.is_unique = True obj.save() self.message_user(request, "This villain is now unique") return HttpResponseRedirect(".") return super().response_change(request, obj) Any Idea how I can fix this!! -
Use clean() method with Django
I'm wondering how I can set a clean method in my form, because I believed my function was well-written, but I don't know why she's not called. I have a simple model : class Document(models.Model): ... format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES, null=False, blank=False) upload = models.FileField(upload_to='media/files/', validators=[validate_file_extension], verbose_name=_('document file'), null=False, blank=False) I have a form : class DocumentForm(forms.ModelForm): def clean(self): cleaned_data = super().clean() upload = cleaned_data.get("upload") file_format = upload.split(".")[-1] format = cleaned_data.get("format") if upload and format: if format != file_format: raise forms.ValidationError("Incorrect format and file format") def __init__(self, *args, **kwargs): super(DocumentForm, self).__init__(*args, **kwargs) for key in self.fields: self.fields[key].required = True class Meta: model = Document fields = ['format', 'upload'] This method has to check if choosen format and file upload extension are the same or not. If not, it should return an error. But I don't know why this function is not called in my view. Because DocumentForm is included into a formset and the formset is well called. Do you have any idea ? -
How to Subtract annoted values in django?
I am unable to subtract annotated values of two different queries in django views. I tried this: qs = Stockdata.objects.filter(User=self.request.user, Company=company_details.pk, Date__gte=selectdatefield_details.Start_Date, Date__lte=selectdatefield_details.End_Date) total = qs.annotate(the_sum=Coalesce(Sum('salestock__Quantity'),0)).values('the_sum') total2 = qs.annotate(the_sum2=Coalesce(Sum('purchasestock__Quantity_p'),0)).values('the_sum2') totalqty = total2 - total I tried using Coalesce from django.db.models.function but getting this error TypeError: unsupported operand type(s) for -: 'QuerySet' and 'QuerySet' Is there any function in django to subtract values? Do anyone have any idea what I am doing wrong in my code? -
Create record in model using ContentType
I want to create my own approve system, but I got stuck at some point, I do not know how to create a model if it is approved with all data in a given model. My model looks like: class historyObject(models.Model): object_type = models.ForeignKey(ContentType, related_name='%(class)s_object', on_delete=models.PROTECT) object_id = models.PositiveIntegerField(null=True, blank=True) object = GenericForeignKey(ct_field="object_type", fk_field="object_id") class Movie(HistoryModel): title = models.CharField(max_length=200, unique=True) slug = extension_fields.AutoSlugField(populate_from='title', blank=True) pub_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) My question is, as with the help of content type, if the status == Approved, it created a model in Movie -
Different field type serialiser - Django Rest Framework
Hello I have a serialiser and I'd like to have one field type for the GET requests and anther field for the POST requests. These are my serialisers: class TypeSerializer(serializers.Serializer): id = serializers.CharField() name = serializers.CharField(max_length=50) colour = serializers.CharField(max_length=8) class UserSerializer(serializers.Serializer): id = UUIDField(format="hex_verbose") name = serializers.CharField() type = TypeSerializer() So the response is something like this: { "id": "987328lf-93ad-21ba-2648-h2u7b95d5cf", "name": "name", "type": { "id": "RANDOM_ID", "name": "Type 1", "colour": "#ffffff" } } That's what I want on the GET, but on the POST I'd like to send a payload like this: { "name": "New name", "type": "RANDOM_ID" } I will get a 500 error because type is expected to be a dictionary. Anyone knows if its posible to have one field for GET and another field for POST without creating another serialiser? -
Django DetaView with simple method get
I have a CBV DetailView and I would like to implement a search form in it. But when I do this, the usual query through this class does not work. Now I implement a search through a similar class. How to implement everything in one class. Below is a listing. (Google translator) urls.py app_name = 'main' urlpatterns = [ ... path('transmitter/<int:pk>', TransmitterDetailView.as_view(), name='transmitter'), path('transmitter', TransmitterSearchDetailView.as_view(), name='search'), ... ] views.py @method_decorator(login_required, name='dispatch') class TransmitterDetailView(DetailView, MultipleObjectMixin): model = Transmitter paginate_by = 5 def get_context_data(self, **kwargs): state_list = self.object.state().filter().order_by('-timestamp') context = super().get_context_data(object_list=state_list, **kwargs) return context @method_decorator(login_required, name='dispatch') class TransmitterSearchDetailView(DetailView, MultipleObjectMixin): model = Transmitter paginate_by = 5 def get(self, request, *args, **kwargs): self.object = Transmitter.objects.get(id_transmitter=request.GET.get('id')) state_list = self.object.state().filter().order_by('-timestamp') context = super().get_context_data(object=self.object, object_list=state_list, **kwargs) return self.render_to_response(context) def get_context_data(self, **kwargs): state_list = self.object.state().filter().order_by('-timestamp') context = super().get_context_data(object_list=state_list, **kwargs) return context transmitter_list.html <form id="searchbar" action="{% url 'main:search' %}" method="get"> {% csrf_token %} <input class="form-control mr-sm-2" type="text" name="id" placeholder="Поиск" aria-label="Поиск"> <hr> <button class="btn btn-outline-success my-2 my-sm-0" type="submit" value="Search">Найти</button> <hr> </form> -
Is there any python library or module for xfa form filling or import data?
I have a xfa form which I want to fill programmatically. I searched for python library for xfa form but couldn't find any library/module. I'm using pdfjinja for filling acroforms but it doesn't work for xfa forms. Can anyone suggest any python library/modules for filling xfa form using xdp file or similar to that. -
Integrating Fullcalendar with django
Can anybody tell me how to integrate fullcalendar in Django? Can you give me an example? I want to input the event using Django admin. -
multiplatform app in python using django or kivy
I have written an app in Python, that I deployed to Linux and Windows thank to cxfreeze. However, there are some limitations of course: a machine with each kind of os is needed to create an executable (including 32 bits or 64 bits versions for instance) ; I can't create an app for android or iOS. I am thinking of other solutions to make my app used on other os like android or iOS. 1) Creating a web app with Django for instance ; however, since my app is not a real web app, I would like to use it only locally, on the machine of the user, the same way the developper can test his app through the runserver function. I thought that this way, the app would work through the web browser on any machine and any os. Is it stupid ? 2) Using Kivy : I read that it is intended to multiplatform deployment. Is it necessary to create each specific executable program on a machine with each kind of os ? Thanks in advance for your advice ! :-) -
Forbidden You don't have permission to access / on this server. On my Virtual Hosting | 403 Forbidden (pid208)
I upload my project files which I tested on my localhost to virtual payed host. I accidentally delete built-in files. Now I have this error Forbidden You don't have permission to access / on this server. 403 Forbidden (pid208) -
Django queryset returns nothing for character 'i' in CharField
I'm trying to write search view to find records by filtering with icontains in a CharField in sqlite table. But some records starts with 'İ' and queryset returns nothing when user submits search form with typing 'i' instead of 'İ'. If record starts with 'i' view runs correctly. Also I ran SQL query for the same table with using LIKE but query returned nothing. Django 2.0 Sqlite 3 -
Unable to get dynos to start on Heroku
I am trying deploy my app on Heroku. I am new to this btw. Atm i am not able to get heroku ps:scale web=1 command to work. Failing with Couldn't find that process type (web). I can confirm i have my Procfile ready with the following entry, web: gunicorn pages_project.wsgi --log-file - The error as per the log file is, 2018-12-05T10:19:11.205407+00:00 heroku[router]: at=error code=H14 desc="No web processes running" I had no issues using git to sync between Bitbucket and Heroku. I could not find an option to add a dyno using the Heroku dashboard. I searched around and found this article on Medium How to Deploy a Django App to Heroku in 2018 but i still can't get it to work. I am using a virtualenv and my project has the following components, dj-database-url==0.5.0 Django==2.1 django-heroku==0.3.1 gunicorn==19.8.1 psycopg2==2.7.6.1 pytz==2018.7 whitenoise==4.1.2 Can someone help me on this ? Thank you. -
How to import csv file and save the content as model with correct number of columns using dJango
I am new to dJango. I have a lot of csv files which have different number of columns. Importing a csv file and then saving it as database using model.py in dJango is a little bit simple. However, the problem is that my files have different number of columns. For example, file A has 3 columns, file B has 13 columns and file C has 22 columns. In this case, should I code each model for three different files? In there a better way which can save any files without writing similar codes in model.py? -
Create multiple types of custom users in Django 2
I'm working on a project using Python(3.6) and Django(2.1) in which I need to create multiple types of users. Note: I have searched a lot but very confused about my specific case, so don't mark this duplicated, please! Here's my scenario: I need to user types first is admin and second is driver. Admin will be able to manage all of the administrative things and also assign orders to the available drivers, and driver will be able to see assigned order when logged into the site. Fetchers (drivers) Can only complete an order and view orders assigned to them. Can receive orders by dispatchers (If logged into backend. Otherwise drivers not logged in will not appear for admin to see as available drivers) Dispatchers (admin) Has the ability to assign pending orders to drivers that are available. Has the ability to cancel order and void. Has the ability to export data from database. Superadmin (owner) confirms drivers and deletes drivers. Can edit driver profile information such as license plate numbers and photos. Can create items for grocery and edit information. Can update pickup/errand prices such as Fast food pick up $4.00 and add auto parts pick up $6.00. Superadmin can … -
Receiving data from related model
I have an model called Participant, who can have Custom Questions, which is its own model: class CustomQuestion(models.Model): SCOPE_REGISTRATION = "registration" SCOPE_PARTICIPANT = "participant" SCOPE_EVENT = "event" program = models.ForeignKey("Program", related_name="custom_questions") scope = models.CharField( verbose_name="Scope", choices=SCOPE_CHOICES, null=False, max_length=50 ) description = models.CharField( verbose_name=u"Description", null=True, blank=True, max_length=100 ) label = models.CharField( verbose_name="Question", null=False, blank=False, max_length=80 ) type = models.CharField( verbose_name="Type", choices=TYPE_CHOICES, default=TYPE_TEXT, max_length=15 ) required = models.BooleanField( verbose_name="Required", null=False, default=False ) choices = models.TextField( verbose_name="Answer Choices", blank=True, null=True, ) Those questions also have an answer: class CustomAnswer(models.Model): class Meta: order_with_respect_to = 'question' question = models.ForeignKey( "CustomQuestion", verbose_name="Question", related_name="answers", on_delete=models.CASCADE ) object_id = models.PositiveIntegerField() content_type = models.ForeignKey( ContentType, limit_choices_to=( models.Q(app_label='core', model='Event') | models.Q(app_label='core', model='Registration') | models.Q(app_label='core', model='Participant') ), on_delete=models.CASCADE ) content_object = GenericForeignKey( 'content_type', 'object_id' ) text = models.TextField( verbose_name="Answer" ) In my front end when my participant is in the register process, I am adding those questions (via Coffeescript, Chaplin/Backbone) to his session, let them answer the questions and then when they filled out the form I validate all the data through my API and save it: participant_questions = session_participant.get("custom_questions") for question in program.custom_questions.filter(scope=CustomQuestion.SCOPE_PARTICIPANT): get_question = next((item for item in participant_questions if item['id'] == question.id), None) try: answer = get_question['answer'] except … -
django event attendee list / user events list foreign key backward search chain
I am making something like a party planner. I want users to be able to confirm their attendance, with the option of canceling later. I want to display a list of attendees on the event page, and a list of events confirmed to be attended on each users profile page. I also want to use attendance to opt in to update emails about those events. I have a Model for the Event: class Event(models.Model): title = models.CharField(max_length=50) date_of = models.DateField(default=datetime.date.today) date_added = models.DateTimeField(auto_now_add=True,) added_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title and a Model for Attendance - to link Users as attendees to Events: class Attendance(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='event') attendee = models.ForeignKey(User, on_delete=models.CASCADE, related_name='attendee') is_attending = models.BooleanField(default=False) def __str__(self): return "%s - %s" % (self.event, self.attendee) The View for the Event is @login_required def event(request, event_id): event = get_object_or_404(Event, id=event_id) shopping_list = event.item_set.order_by('date_added') form = VSLForm() attendee_list = event.event.all() print("\n\n\n\n" + str(attendee_list) + "\n\n\n\n") context = {'event': event, 'shopping_list': shopping_list, 'form': form} return render(request, 'VSL/event.html', context) I have a View for a button to confirm attendance @login_required def is_attending(request, event_id): """set user as attending an event.""" event = get_object_or_404(Event, id=event_id) attendance = Attendance( attendee = request.user, event = … -
Why can't / How can I get the address of the logged in user?
I'm new to Django and I'm trying to get the addres of the logged in user in my Evaluation-model by adding the attribute address to the User-table of Django but I cannot do it.. I am getting ( AttributeError: 'ReverseOneToOneDescriptor' object has no attribute 'address' ) when I'm typing py manage.py makemigrations MyApp in the terminal. Those are my imports: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver This is the class I created wich has to add the attribute adress to the User-table: class UserAdress(models.Model): user = models.OneToOneField(User, null=True) address = models.ForeignKey(Addresses, null=True) def __str__(self): return str(self.user) + ' • ' + str(self.Address) @receiver(post_save, sender=User) def add_address_to_user(sender, instance, created, **kwargs): if created: UserAdress.objects.create(user=instance) @receiver(post_save, sender=User) def save_address(sender, instance, **kwargs): instance.UserAdress.save() This is the model I created wich it's address attribute has to get the address of the logged in user: class Evaluation(models.Model): id = models.AutoField(primary_key=True) address = models.ForeignKey(UserAddress, default=User.UserAddress.address) evaluation = models.TextField(max_length=1000) -
ManyToManyField in django models
I need to create a set of models like this: class Step(models.Model): field1 = models.CharField(max_length=50) field2 = models.CharField(max_length=50) class Scenario(models.Model): name = models.CharField(max_length=50) steps = models.ManyToManyField(Step, related_name="scenarios") The thing is I want the scenario to include several steps in an order that I will specify and even the same step several times. Like this: Scenario1: step1 step2 step1 step3 I want this step's order to be easy editable in admin site. I found out about filter_horizontal, it looks a lot like what I need in admin site, but it has no option to add a step one more time and to move steps up and down. -
How to use Django with multiple databases (each having different tables)?
I have a really weird requirement. I am working on a project where the I have to create two databases and each of them has different tables. To be precise, if I have table_x in db_1 then I should not create table_x in db_1. Is it possible possible in Django? Anz sort of help will be highly appreciated. -
Redirect passing the entry id in the url - Django Python
I am new to django and I have been learning it to build an app and solve a problem/have fun! I want people to go to a Webapp and start to request a valuation for a house without the need for authentication! I wish hat after they submit the data to the database they are redirected to page that contains the entry id in the database: Views.py: from django.shortcuts import get_object_or_404, render, redirect from .models import AddValue def valuation(request): if request.method == 'POST': rua = request.POST['rua'] andar = request.POST['andar'] concelho = request.POST['concelho'] valuation = AddValue(rua=rua, andar=andar, concelho=concelho) valuation.save() return redirect(request,'valuator/'+id+'.html') def ai_value(request, query_id): query = get_object_or_404(AddValue, pk=query_id) return redirect('valuator/id') Urls.py: from django.urls import path from . import views urlpatterns = [ path('valuation', views.valuation, name='valuation'), path('', views.index, name='index'), path('<int:query_id>', views.ai_value, name='value'),] So I after the form is filled and saved I would like the redirect to be with the slug of the entry they just created. Many thanks. -
How to use Django queries on a different machine
I have two servers. One is for database/Django (Machine A) the other one is for calculating stuff (Machine B). How could I enter data from Machine B to the database on Machine A while using django models.