Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update a model field using templates?
I am working on a project that allows users to register, but the model contains a verified field and only admin can change it. User can log in only when verified = True. Also, I need to implement that once a user is verified, he gets notified through a mail. Is there a way to connect the mail url to the verified field? If it can be done through templates, How? I want to redirect to mail url as soon as admin updates the verified field. -
Why is form_valid not getting the sent POST parameters?
I am trying to send a POST request with a parameter by using a form with a hidden input in Django. However, the receiving view does not get the POST parameter I am sending. Here's the form in my post_detail.html template: <form action="{% url 'something-create' %}" method="POST"> {% csrf_token %} <input type="hidden" name="id_name" value="2"> <button type="submit">Add</button> </form> Then, here's the view that is called by the 'something-create' url pattern: class SomethingCreateView(CreateView): model = Something template_name = "something_create.html" def form_valid(self, form): # id_name always returns None... id = self.request.POST.get("id_name") if id is not None: form.instance.sm = Something.objects.get(id=int(id)) return super().form_valid(form) Can anyone tell me what I'm doing wrong? Thank you in advance. -
how to fix a problem where a django template isn't displayed correctly in the email
I have a template which is supposed to display an html template for a reset password. I do receive the email, but the result is not the template itself but the code inside the template. I've tried to see if there was any error in the html file, but i didn't find any What is inside the Template is only HTML code : <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Réinitialisation de votre mot de passe</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> ... ... ... I do receive the email but i receive the code inside the file, not the compiled html code. Thank you -
Proper way to do Mixins for Django models
I have the following mixins: class AbandonableMixin(object): is_abandoned = models.BooleanField( default=False, verbose_name=_('Abandoned?')) class ReadyMixin(object): is_ready = models.BooleanField( default=False, verbose_name=_('Ready?')) class StoppableMixin(object): is_stopped = models.BooleanField( default=False, verbose_name=_('Stopped?')) I would like to use these in my class like ordinary mixins: class MyObject(models.Model, AbandonableMixin, StoppableMixin): ... class MySecondObject(models.Model, ReadyMixin, StoppableMixin): ... This results in the following error: TypeError: Cannot create a consistent method resolution order (MRO) for bases Model, AbandonableMixin What am I doing wrong? -
How to compare queryset size with another queryset?
I have three querysets and I want the maximum size among all. from django.shortcuts import render from .models import Resources, Journey_template, Topic_Table, Subtopic_Table def Journey_view(request) : if (Journey_template.objects.filter(subtopic_id=1).exists()): # obj = Journey_template.objects.filter(subtopic_id=1) completed_obj = Journey_template.objects.filter(subtopic_id=1, status='completed') pending_obj = Journey_template.objects.filter(subtopic_id=1, status='pending') skipped_obj = Journey_template.objects.filter(subtopic_id=1, status='skipped') # print(completed_obj.count(), pending_obj.count(), skipped_obj.count()) # print(obj.count()) # return render(request,'journey-page.html',{'data': obj}) else: obj = Resources.objects.filter(topic_id=1,subtopic_id=1) # Id = Topic_Table.objects.get(id=topic_id) for resource in obj: print(resource.resource_id) Journey_template(subtopic_id=resource.subtopic_id, resource_id=resource, topic_id=topic_id).save() return render(request,'journey-page.html',{'completed' : completed_obj, 'pending' : pending_obj, 'skipped' : skipped_obj}) Is there any inbuilt function which returns maximum size. -
Django: Aggregate per "event__pk"
I get these query results <QuerySet [{'event__pk': 4, 'pk': 15, 'total_gross': 12340000}, {'event__pk': 4, 'pk': 13, 'total_gross': 123000}, {'event__pk': 5, 'pk': 22, 'total_gross': 1234000}]> The problem I'm dealing with is I am trying to aggregate total_gross per event. However, always when I add .aggregate(Sum('total_gross')), Django is just aggregates everything. Any idea how to fix that? max_total_gross_per_ticket = ( Ticket.objects.filter( event__organizer__in=self.organizers, event__status=EventStatus.LIVE, ).values('event__pk', 'pk') .order_by('event__pk') .annotate( total_gross=F('quantity') * F('price_gross'), ) # .aggregate(Sum('total_gross')) ) -
Handling one to one relationship between django models
I am having a one to one relationship between 2 models. While creating the second model, I want to pass the instance of the first model to the second one. These 2 models are new tabs/features in our web application. I tried passing the instance through URL but didn't succeed. Maybe I am not following steps correctly. Details about: python version: Python 3.6.4 :: Anaconda, Inc. django version: 2.0.2-3 Please find below the code: 1) models.py class StudyConcept(models.Model): requestor_name = models.CharField(max_length=240, blank=False, null=False) project = models.CharField(max_length=240, blank=False, null=False) date_of_request = models.DateField(blank=False, null=False) brief_summary = models.CharField(max_length=4000, blank=False, null=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.id) class Logistics(models.Model): budget = models.CharField(max_length=255, blank=False, null=False) business_technology = models.CharField(max_length=3, choices=CHOICES, blank=False, null=False) vendor_or_contracts = models.CharField(max_length=3, choices=CHOICES, blank=False, null=False) studyConcept = models.OneToOneField(StudyConcept, on_delete = models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.id) def get_absolute_url(self): return reverse('update_Logistics', kwargs={'pk': self.pk}) def get_deliverablesLogistics(self): return ','.join([str(i) for i in self.deliverablesLogistics.all().values_list('id', flat=True)]) def get_paymentScheduleLogistics(self): return ','.join([str(i) for i in self.paymentScheduleLogistics.all().values_list('id', flat=True)]) def get_commentsLogistics(self): return ','.join([str(i) for i in self.commentsLogistics.all().values_list('id', flat=True)]) class DeliverablesLogistics(models.Model): milestone_deliverable = models.CharField('MileStone/Deliverable', max_length=480, blank=False, null=False) poa = models.CharField('POA', max_length=480, blank=False, null=False) start_date = models.DateField(blank=False, null=False) end_date = models.DateField(blank=False, null=False) logistics = models.ForeignKey(Logistics, related_name='deliverablesLogistics', on_delete=models.CASCADE) def __str__(self): … -
Creating a form based on a list of sporting fixtures then capturing the scores for these
I'm creating an app to record predictions for a set of 10 football fixtures every week. To generate the form I want to return a list of the 10 fixtures defined in the database form for the current game week. Then the user will input the scores and it will be saved to entry_data model I've tried many varations of and closest I've got is with inlineformset_factory but this only works with a single object. How can initiate this with all 10 fixtures? I feel I could hack this to work with loops and generating many formsets but feel there must be a more elegant way Models.py #to save entries class entry_data(models.Model): team_id = models.ForeignKey(usr_teams, models.CASCADE) fixture_id = models.ForeignKey(Fixtures, models.CASCADE) score_home = models.PositiveIntegerField(default=0) score_away = models.PositiveIntegerField(default=0) # list of fixtures for each gameweek class Fixtures(models.Model): home_team = models.ForeignKey(Teams, models.CASCADE) away_team = models.ForeignKey(Teams, models.CASCADE) game_week = models.ForeignKey(configdata, models.CASCADE) class configdata(models.Model): gameweek = models.PositiveIntegerField(default=0) season = models.PositiveIntegerField(default=2019) gw_deadline = models.DateTimeField(default=datetime.now) gw_active = models.BooleanField(default=False) gw_closed = models.BooleanField(default=False) Forms.py class score_entry(forms.ModelForm): class Meta: model = entry_data exclude = () Views.py def get(self, request): gameweek = '1' fixtures = fix.objects.get(game_week__gameweek='1')) FixtureFormSet = inlineformset_factory(Fixtures, entry_data, form = score_entry, extra=0, can_delete=False) formset = FixtureFormSet(instance = fixtures) return … -
How to tell if the data entered was through django admin or through HTML form linked with django?
I am new to django platform. And I wanted to add a feature where you can tell if the data entered (let's say an advertisement) was done through django admin portal or through HTML form which is collecting data from user(let's say an advertisement). And so I would be able to determine if it was someone inside the organization who entered the data using django admin or was it some user outside the organization who has given this data. And further I want to sort the data accordingly. -
Accessing Child model via DetailView?
i have two models Farmer and Animals. Animal(s) are related to Farmer(s) via ForeignKey. As you see below in the Template, i want to display a farmer and with his related animals. My Template displays the first_name, last_name and city, correctly the only missing are the related animals from the child model. In other projects i used "{% for item in ParentModel.ChildModel_set.all %}" to access the child model unfortunately it does not work this time. Is that because i used a DetailView? models.py class Farmer(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) city = models.CharField(max_length=40) objects = FarmerManager() # --- link to Manager def __str__(self): return self.last_name def get_absolute_url(self): return reverse("datainput:farmer_detail", kwargs={"id": self.id}) class Animal(models.Model): name = models.CharField(max_length=40) weight = models.DecimalField(max_digits=5, decimal_places=2) species = models.ForeignKey('Species', on_delete=models.CASCADE) farmer = models.ForeignKey('Farmer', related_name='farmername', on_delete=models.CASCADE) objects = AnimalManager() # --- link to Manager def __str__(self): return self.name def get_absolute_url(self): return reverse("datainput:animal_detail", kwargs={"id": self.id}) views.py class FarmerDetailView(DetailView): template_name ="datainput/farmer_detail.html" queryset = Farmer.objects.all() def get_object(self): some_id = self.kwargs.get("id") return get_object_or_404(Farmer, id=some_id) urls.py <...> path('farmer/<int:id>/', FarmerDetailView.as_view(), name='farmer_detail'), <...> farmer_detail.html <...> <div class="row" id="p1"> <div class="col-6 offset-md-3"> <p> Bauer {{ farmer.first_name }} {{ farmer.last_name }}</p> in {{ farmer.city }} {% for animals in farmer.animal_set.all %} <p> {{ animals }} … -
Moving the user to the same place, after completing the form at the bottom of the page in Django
After choosing the option, I want to transfer the user to the same place. Can I do it in Django without using JavaScript? Example Video The user can not see whether he has completed the form correctly or not, it is misleading. It must scroll down the page again. -
would i get charged more if i set my website to get "GET" every fifteen second
i finished my first app, and in my app I have django-notification-app which has "GET /inbox/notifications/api/unread_list/?max=5 HTTP/1.1" 200 2249 every fifteen second. (the app checks if the user has a notification every fifteen second) I'm not sure what they mean by data when registering linux server, does that mean the data I can store in db? in that case django notification shouldn't be a problem or Would I get charge a lot if my app checks that every fifteen second? -
|as_crispy_field got passed an invalid or inexistent field
I am trying to display an empty form after an email is sent. In my views.py I have: send = False if request.method == 'POST': form = PhoneContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data topic = 'Klient prosi o kontakt Tel.: %s o godzinie %s' %(cd['number'], cd['data_contact']) to = ['biuro@e-bluedesign.co', ] send_mail(topic, topic, 'benjamin.langeriaf7@gmail.com', to) send = True else: form = PhoneContactForm() if send: form = EmailContactForm() Everything works fine if the form calls in the template in this way. {{ form|crispy }} But when I try this: {{ form.number|as_crispy_field }} {{ form.data|as_crispy_field }} I Receive information: |as_crispy_field got passed an invalid or inexistent field Why am I getting this information in my second approach? it seems to me that everything is done correctly, if the field send="True" my view again receives an empty form, so why is the error returned in the template. Any help will be appreciated. -
What is pickling in Python/Django?
I've just started getting into python and Django and I came across pickling, but I'm still not sure what it actually does. The documentation for django says, "When you pickle a model, its current state is pickled." That doesn't really help much. So for example if I pickle something, does it just store the data like a temp variable? I'm sure this is an easy question, also, is pickling even necessary? Any information is helpful, thanks! -
Django + Heroku + GoDaddy = SSL_ERROR_INTERNAL_ERROR_ALERT
I am having trouble connecting my Heroku App (Django) to my GoDaddy Domain. Whenever I input my domain name in the URL bar an SSL_ERROR_INTERNAL_ERROR_ALERT error occurs. Can someone please enlighten me on how to fix this. Here are screenshots of my Heroku and GoDaddy settings: Heroku Settings https://res.cloudinary.com/nthnyvllflrs/image/upload/v1560531096/3.png GoDaddy DNS Settings https://res.cloudinary.com/nthnyvllflrs/image/upload/v1560531098/2.png GoDaddy Forwarding Settings https://res.cloudinary.com/nthnyvllflrs/image/upload/v1560531097/1.png -
Error trying to uploading a image from a form django
i am trying to upload a image from a form that i am building. As i said in the title, my error is the file is not uploaded. And i dont know where is the mistake, here is my models.py: def upload_location(instance, filename): return "uploads/%s/img/%s/" % (instance.id, filename) class CustomUser(AbstractBaseUser, PermissionsMixin): ... width_field = models.IntegerField(default=0) height_field = models.IntegerField(default=0) photo = models.ImageField( upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field" ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() ... The problem is the "photo" field. Here is form where i am calling this: class UserConfigurationForm(UserChangeForm): class Meta: model=CustomUser fields = ( 'photo', 'password' ... ) My template where i am calling the form: <form method="POST"> {%csrf_token%} <input type="file" name="photo" accept="image/*"> ... <!--SUBMIT--> <div class="form-group"> <div class="col-xs-12"> <br> <button class="btn btn-lg btn-success" type="submit"><i class="glyphicon glyphicon-ok-sign"></i> Guardar cambios</button> </div> </form> Finally, this is my views.py: def configuration(request): form = UserConfigurationForm(request.POST or None, instance=request.user) if form.is_valid(): form.save() return redirect('myuser:myuser') else: form = UserConfigurationForm(instance=request.user) return render(request, 'myuser/configuration.html', {'form': form}) So, if you can tell me where is my mistake from all of this, i´ll be appreciated. Thank you. -
How to fix 'NoneType' object error in firefox with djangoframework
When the browser get data in specially firefox and IE edge, I am getting error message attached code, It's fine in chrome My developement environment is conda 4.6.14 Conda package lists are liek those asn1crypto 0.24.0 pypi_0 pypi ca-certificates 2019.5.15 0 certifi 2019.3.9 pypi_0 pypi cffi 1.12.3 pypi_0 pypi chardet 3.0.4 pypi_0 pypi cryptography 2.7 pypi_0 pypi django 2.2.2 pypi_0 pypi djangorestframework 3.9.4 pypi_0 pypi idna 2.8 pypi_0 pypi openssl 1.1.1c he774522_1 pip 19.1.1 py37_0 pycparser 2.19 pypi_0 pypi pyopenssl 19.0.0 pypi_0 pypi python 3.7.3 h8c8aaf0_1 pytz 2019.1 pypi_0 pypi requests 2.22.0 pypi_0 pypi setuptools 41.0.1 py37_0 six 1.12.0 pypi_0 pypi sqlite 3.28.0 he774522_0 sqlparse 0.3.0 pypi_0 pypi urllib3 1.25.3 pypi_0 pypi vc 14.1 h0510ff6_4 vs2015_runtime 14.15.26706 h3a45250_4 wheel 0.33.4 py37_0 wincertstore 0.2 py37_0 I am supposed to think the problem is not relative to code written in my django project and application. Maybe the problem is about anaconda system. I dont know exactly. Call stack is as I attached. Not Found: /favicon.ico [15/Jun/2019 01:14:44] "GET /favicon.ico HTTP/1.1" 404 2077 Traceback (most recent call last): File "C:\Users\sam\Anaconda3\envs\drfenv\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\sam\Anaconda3\envs\drfenv\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\sam\Anaconda3\envs\drfenv\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\sam\Anaconda3\envs\drfenv\lib\wsgiref\handlers.py", line 332, … -
Laravel, DJango, Oracle Migration
In Laravel and DJango, there are options to migrate a table from one form (ex: with 5 columns) to another form (ex: 6 columns). This is done through the use of makemigrations and migrate. I am working with FLEX, Docker, Python and Orcle. I am not using DJango or Laravel. How can one get the same functionality under these conditions? TIA -
The view myapp.views.home didn't return an HttpResponse object. It returned None instead
am trying to create a todo list with django, but for some reason am getting this error when i try to show the date in my screen The view myapp.views.home didn't return an HttpResponse object. It returned None instead. MY CODE from django.shortcuts import render, redirect from .models import List from .forms import ListForm from django.contrib import messages def home (request): if request.method == 'POST': form = ListForm(request.POST) if form.is_valid(): form.save() all_items = List.objects.all messages.success (request, ('Item has Been Added to List!')) return render (request, 'home.html', {'all_items': all_items}) else: all_items = List.objects.all return render(request, 'home.html', {'all_items': all_items}) -
auth is returned as none when trying to log in user when signing up
I am trying to solve the use case where when user signs up then the user is automatically logged in and return the token of that user so that i can that token in cookies from frontend. However, I get issue "Email already registered". when i debug my code using pdb, i found that auth = authenticate(username=email, password=password) is returning None. How can I authenticate user during signup and pass token of that user? Here is how i am doing class Register(graphene.Mutation): ''' Mutation to register a user ''' class Arguments: email = graphene.String(required=True) password = graphene.String(required=True) password_repeat = graphene.String(required=True) success = graphene.Boolean() errors = graphene.List(graphene.String) email = graphene.String() def mutate(self, info, email, password, password_repeat): if password == password_repeat: try: serializer = RegistrationSerializer(data={ 'email': email, 'password': password, 'is_active': False }) if serializer.is_valid(): user = serializer.save() auth = authenticate(username=email, password=password) import pdb pdb.set_trace() # login user and pass the token login(info.context, auth) return Register(success=bool(user.id), email=user.email) else: print("error", serializer.errors) except Exception: errors = ["email", "Email already registered"] return Register(success=False, errors=errors) errors = ["password", "Passwords don't match."] return Register(success=False, errors=errors) class Login(graphene.Mutation): """ Mutation to login a user """ class Arguments: email = graphene.String(required=True) password = graphene.String(required=True) success = graphene.Boolean() errors = graphene.List(graphene.String) … -
Select multiple choices and store ordering in django admin page
I have a models.Model class, and an Admin class that's working the form on the Django Admin page. I want to create a table (similar to a m2m table) that can select multiple selections and keep the ordering. How can I accomplish this? -
Changing the URL has no effect on JSON Returned DjangoRest Framerwork
I am trying to filter a list of my customers stored and return a specific one when I try (xxx/api/customers/fred) it returns all customers and whatever is entered after the customers/ has no effect on the JSON returned Views class CustomerListAPIView(generics.ListAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer class CustomerRetrieveAPIView(generics.RetrieveAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer lookup_field= "name" Serializers class CustomerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Customer fields = ['name' , 'address', 'phonenumber'] Urls url(r'^api/customers/', views.CustomerListAPIView.as_view(), name = "customer_list"), url(r'^(?P<slug>[\w-]+)/$', views.CustomerRetrieveAPIView.as_view(), name='retrieve'), ive also tried to override def get_queryset(self, *args, **kwargs): but this method doesn't seem to get triggered when a url is entered -
Formset Data Initialization
I'm trying to understand how the initialization of formset data works. To create a formset you use formset_factory and define arguments "extra" and "max_num", which determine the number of extra blank forms after the initial/filled forms and the max number of forms posted respectfully. But then, when you create an instance of the defined formset to pass to the template as data, you pass into that instance more data, specifically 'form-TOTAL_FORMS', 'form-INITIAL_FORMS', and 'form-MAX_NUM_FORMS'. But haven't we already defined in the formset_factory the max_num_forms? Why are we defining this twice? For documentation initial forms seems to be just what it sounds--forms already filled in, which is different than "extra". Just don't understand defining the max arg twice. -
Cant download a product Image product file in Django 2.2
Hello am working with django 2.2 i have created a product download function and but still a product cant download it just previews when the download link is clicked. views.py def download_product(request,filename): filepath = os.path.join(settings.MEDIA_ROOT,filename) guessed_type = guess_type(filepath)[0] wrapper = FileWrapper(open(filepath,'rb')) mimetype = 'application/force-download' if guessed_type: mimetype = guessed_type response = HttpResponse(wrapper, content_type=mimetype) response["Content-Disposition"] = "attachment; filename=%s" % smart_str(filename) response["X-SendFile"] = filepath return response urls.py urlpatterns = [ url(r'^', product_list, name='product-list'), url(r'^(?P<slug>.*)/download/(?P<filename>.*)$',download_product,name="download_product") ] and inside my template {% if object.download %} <p><a href='{{ object.download.url }}'>Download</a></p> {% endif %} -
Suddenly I am getting 502 on an End point, rest are working fine
I am serving django project with gunicorn, It running fine but after some time on one specific endpoint start giving 502. Other api end point still okay and giving proper response. I already tried with gunicorn service settings Current setting ExecStart=/var/virtualenv/d/bin/gunicorn --workers 5 proj.wsgi:application -b :9008 --threads 8 -k gthread --timeout 120 47.247.243.245 - - [14/Jun/2019:15:02:11 +0000] "GET /api/user/1263/league/81/ HTTP/1.1" 200 291 "-" "okhttp/3.12.1" 157.32.16.35 - - [14/Jun/2019:15:02:11 +0000] "GET /api/v1/xyc-leaderboard/?contest=4973 HTTP/1.1" 200 43714 "-" "okhttp/3.12.1"" 157.32.16.35 - - [14/Jun/2019:15:02:16 +0000] "GET /api/v1/xy/xy-team/15543 HTTP/1.1" 301 5 "-" "okhttp/3.12.1" 157.32.16.35 - - [14/Jun/2019:15:02:16 +0000] "GET /api/v1/xy/xy-team/15543/ HTTP/1.1" 502 5517 "-" "okhttp/3.12.1" 171.76.167.124 - - [14/Jun/2019:14:39:56 +0000] "GET /api/v1/xy/xy-team/15343/ HTTP/1.1" 502 182 "-" "okhttp/3.12.1"