Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: redirect to another page after download is triggered
I would like the user to be redirected to another page after the download of his file is triggered. How should I do this? Below is my code on how the download is triggered. Alternatively, how could I parse the data frame created in the first web page to the web page the user is redirected to then trigger the download? Any help is appreciated. Thank you! from django.shortcuts import render from django.http import HttpResponse from .forms import * from .functions import * from . import models def index(request): if request.method == 'POST': # upload file file=request.FILES['excelfile'] df=createDF(file) # write to xlsx and trigger download response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="somefile.xlsx") df.to_excel(response, index=False) return response # render form for upload return render(request, 'webpage/index.html') -
Use multiple databases in Django having the other database contain tables not created by any model
Here are my questions and if you want to know the details, kindly refer further below (Sorry for the long post, I wanted the inquiry to be as detailed as possible): Questions Is it possible to retrieve data from an external database and use those inside your Django project even if the tables in that database are NOT created as models? If so, what's the basic concept to achieve such. If NOT, then the workaround left is to use the SAME DATABASE as the remote one, and save all models of the django project into a specific schema in that database? So we are trying to forcibly implement Cross-database referencing with a remote database my_remote_db, that contains tables which are not created by a Django model. We've read the Django doc telling it currently cannot handle such referencing method, but the fact we can define multiple databases in settings.py makes us optimistic that there is somehow a workaround. Databases as defined in our settings.py django_project_db - main database (the one used by our Django project for its models) my_remote_db - the remote database. Several applications are using this database e.g. our Scout and PHP applications, etc. What we want to … -
Django Admin Custom Url Path
Hi I would like to create a custom url in my django admin. The default URL when editing an object is. http://localhost:8000/admin/cart/cart_id/change In my admin http://localhost:8000/admin/cart/1/change I have a field called cart unique id. I want to create a custom url that behaves similar to the edit URL in django admin. http://localhost:8000/admin/cart/uniq_id/change http://localhost:8000/admin/cart/H2KPAT/change Is this implemation possible? -
Django Modelform - setting field value to foreign key
I created two models in my app: "Prescription" and "Prescription_status." When a user clicks save on my "Create new prescription" modelform, I need to add a "Prescription_status" to the "Prescription." In the below instance, I'd like to save as a 'Draft' status (PK=1). I don't want to set a default status. I've been trying everything, what am I missing?? Thanks in advance! models.py # Static Prescription Status Types class Prescription_status(models.Model): status = models.CharField(max_length=200) status_definition = models.TextField() def __str__(self): return '%s' % (self.status) # Prescription Model class Prescription(models.Model): order_id = models.AutoField(primary_key=True, unique=True) status = models.ForeignKey(Prescription_status, models.SET_NULL, null=True) I saved the following Prescription_status objects to the database, which I'd like to reference as users save or edit prescriptions: status_id for "Draft" status = 1 status_id for "Ready for Signing" status = 2 status_id for "Signed and Authorized" status = 3 database chart showing PK for each status forms.py class PrescriptionForm(forms.ModelForm): class Meta: model = Prescription fields = ('medication', 'quantity', 'directions', 'refills', 'earliest_permitted_fill_date', 'daw',) widgets = { 'earliest_permitted_fill_date': DatePickerInput(), # default date-format %m/%d/%Y will be used } views.py def new_rx(request): if request.method == "POST": form = PrescriptionForm(request.POST) if form.is_valid(): prescription = form.save(commit=False) prescription.status = Prescription_status.objects.get(pk=form.cleaned_data['1']) prescription.save() return redirect('home') else: form = PrescriptionForm() return … -
How to remove DELETE button from django admin page
I want to remove the Delete button from django admin page as shown below. -
django user fields shown empty in template
cannot access fields in templates model.py: class DSS(models.Model): title = models.CharField(max_length=255, null=True, blank=True, verbose_name='عنوان') usr = models.ForeignKey(User, related_name='owner', verbose_name='کاربر') view.py: def state(request): result = DSS.objects.values('usr').order_by('usr').annotate(count=Count('usr')) context = {'result': result,} return render(request, 'state.html', context) my template: <tr> <td>{{ item.usr }}{{ item.usr.get_username}}{{ item.usr.username}}{{ item.usr.get_full_name}}</td> <td>{% with item.usr.get_username as usrnm %} {{ item.usr.get_full_name|default:usrnm }} {% endwith %}</td> <td>{{ item.usr.first_name }} {{ item.usr.lastname }}</td> <td>{{ item.owner.first_name }}</td> <td>{{ item.count }}</td> </tr> {{ item.count }} work well and {{ item.usr }} just show user id, but I need to display username. -
Python django ImportError: cannot import name (unknown location)
I am starting to use Django and was able to get Django Rest Framework working. Now, I am trying out Elasticsearch using https://django-elasticsearch-dsl-drf.readthedocs.io/en/0.18/ and also following https://github.com/barseghyanartur/django-elasticsearch-dsl-drf/tree/master/examples/simple I followed the examples, built my project along those lines. I am getting the ImportError when I try to start server, could anyone please review and give me pointers on what I may be missing. I am enclosing some details about my environment for reference. Thanks Environment: cmd > pip freeze | find "Django" django-cors-headers==3.0.2 django-elasticsearch-dsl==0.5.1 django-elasticsearch-dsl-drf==0.18 django-filter==2.1.0 django-nine==0.2.2 djangorestframework==3.9.4 Directory structure demosite demosite settings.py [INSTALLED_APPS contains my_rest_app, search_indexes] my_rest_app [which works with http://localhost:8000/my_rest_app/] search_indexes viewsets publisher.py [see below] urls.py [see below] documents publisher.py [see below] search_indexes/url.py --------------------- from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from search_indexes.viewsets import PublisherDocumentViewSet urlpatterns = [ url(r'^', include(router.urls)), ] # ********************************************************** # *********************** Publishers *********************** # ********************************************************** router.register( r'publishers', PublisherDocumentViewSet, basename='publisherdocument' ) search_indexes/viewsets/publisher.py ------------------------------------ from django_elasticsearch_dsl_drf.pagination import LimitOffsetPagination from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet from ..documents import PublisherDocument from ..serializers import PublisherDocumentSerializer __all__ = ( 'PublisherDocumentViewSet', ) class PublisherDocumentViewSet(DocumentViewSet): """The PublisherDocument view.""" document = PublisherDocument serializer_class = PublisherDocumentSerializer search_indexes/documents/publisher.py -------------------------------------- from my_rest_app.models import Publisher __all__ = ('PublisherDocument',) INDEX = Index(settings.ELASTICSEARCH_INDEX_NAMES[__name__]) # See Elasticsearch Indices API reference for … -
How to fix TypeError when using django-restframework-generics
I am learning how to use class-based generic views but I keep getting a type error from invoice.models import Invoice from invoice.serializers import InvoiceSerializer from rest_framework import generics class InvoiceList(generics.ListCreateAPIView): queryset = Invoice.objects.all() serializer_class = InvoiceSerializer class InvoiceDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Invoice.objects.all() serializer_class = InvoiceSerializer I get a type error with the message "init() takes 1 positional argument but 2 were given" -
How to calculate with multiple condition on dictionary python
So I am writing some code in python 3.6, I have a dictionary, I want to sum output_jam and output_ot if jam and cell have same value. this is my code. any one can help me to fix my code data = { 1: {'cell_1': ['13a'], 'jam_1': ['07-08'], 'model_1': ['SUPERSTAR'], 'output_1': ['10'], 'output_jam_1': [''], 'time_1': [''], 'output_ot_1': [''], 'time_ot_1': ['']} , 2: {'cell_2': ['13a'], 'jam_2': ['07-08'], 'model_2': ['SUPERSTAR'], 'output_2': ['20'], 'output_jam_2': [''], 'time_2': [''], 'output_ot_2': [''], 'time_ot_2': ['']} , 3: {'cell_3': ['13a'], 'jam_3': ['07-08'], 'model_3': ['SUPERSTAR'], 'output_3': ['40'], 'output_jam_3': [''], 'time_3': [''], 'output_ot_3': [''], 'time_ot_3': ['']} , 4: {'cell_4': ['13b'], 'jam_4': ['08-09'], 'model_4': ['SUPERSTAR'], 'output_4': ['30'], 'output_jam_4': [''], 'time_4': [''], 'output_ot_4': [''], 'time_ot_4': ['']} , 5: {'cell_5': ['13d'], 'jam_5': ['16-17'], 'model_5': ['SUPERSTAR'], 'output_5': ['40'], 'output_jam_5': [''], 'time_5': [''], 'output_ot_5': [''], 'time_ot_5': ['']} , 6: {'cell_6': ['13d'], 'jam_6': ['16-17'], 'model_6': ['SUPERSTAR'], 'output_6': ['40'], 'output_jam_6': [''], 'time_6': [''], 'output_ot_6': [''], 'time_ot_6': ['']} , 7: {'cell_7': ['13d'], 'jam_7': ['16-17'], 'model_7': ['SUPERSTAR'], 'output_7': ['10'], 'output_jam_7': [''], 'time_7': [''], 'output_ot_7': [''], 'time_ot_7': ['']} , 8: {'cell_8': ['13d'], 'jam_8': ['18-19'], 'model_8': ['SUPERSTAR'], 'output_8': ['60'], 'output_jam_8': [''], 'time_8': [''], 'output_ot_8': [''], 'time_ot_8': ['']} , } output_ = 'output_' output_jam_ = 'output_jam_' output_ot_ = 'output_ot_' time_ = 'time_' … -
What web technology to be used to develop an interactive web app for the Energy Hub model?
I need recommendations regarding the technology to be used in a web app. What the app is about and what I am looking for are described in detail here. I understand that this question is better suited to be asked on https://softwarerecs.stackexchange.com, which is where the link above leads to. Since the StackOverflow community is larger, I felt a need to post it here as well. If this violates any of the community guidelines, feel free to take it down. Please help me out. Mentioning good learning material/tutorials for what you suggest would be a cherry on top. Thanks. -
Django model edit page creates new model instead of editing the current one
I just deployed my first Django app, which is for the small company I work for to track jobs, expenses, and it has a blog for customers to see. After I deployed the site, I realized the page to edit the job model did not show the job's information but a blank form for a new instance. When the edit is submitted it creates a new instance instead of changing the current job that's meant to be edited. Editing works just fine through the admin dashboard, but I just can't figure out why the edit page won't work. I tried tweaking the view function for editing the job, deleting migrations and the database, and re-migrating, all to no avail. views.py def job_edit(request, pk): if request.user.is_authenticated: job = get_object_or_404(Job, pk=pk) if request.method == "POST": form = JobForm(request.POST, request.FILES) if form.is_valid(): job = form.save(commit=False) job.author = request.user job.last_updated = timezone.now() job.image0 = form.cleaned_data['image0'] job.image1 = form.cleaned_data['image1'] job.image2 = form.cleaned_data['image2'] job.image3 = form.cleaned_data['image3'] job.save() messages.success(request, 'Job updated successfully') return redirect('job_detail', pk=job.pk) else: form = JobForm() return render(request, 'job_edit.html', {'form': form}) else: return render(request, 'job_edit.html') forms.py class JobForm(forms.ModelForm): foreman = forms.ChoiceField(choices=FOREMEN, required=True) status = forms.ChoiceField(choices=JOB_STATUS, required=True) zip = forms.IntegerField(validators=[MinValueValidator(00000), MaxValueValidator(99999)]) class Meta: model = … -
How can I structure Django permissions to have multiple categories of permissions groups?
I'd like to have multiples layers of permissions for an API using Django Rest Framework, how can I best achieve this? Specifically the three categories of authorization I have are: Roles: Model level access, such as admin and different customer types. GroupAccess: Per object, group access such as a team of users. Sensitivities: Per object, additional tags for sensitive information. The second two categories apply equally across all models and it would be nice to not need separate permissions for each model. Idea 1: Create a model for each category inheriting from the standard django auth group. Doing these as proxy groups, to be logically different in my code, but as consistent with standard authorization as possible. Then use django-guardian to enable the object level permissions. Idea 2: Use the standard groups for roles and assign model level permissions based on these groups. For the object level permissions write a custom permission classes in Django Rest Framework to check the object level permissions against the user. -
What does base_name do in Django?
router.register(r'my-model/', MyModelView, base_name='MyModel') I don't understand what the base_name is for in the code above. I've read the Django doc: https://www.django-rest-framework.org/api-guide/routers/, and other Stackoverflow questions. But I still don't understand. -
Converting to Django Channels 2.0 how to serve static pages from runserver
Channels 1.0 I was able to serve my http pages in development runserver using: urlpatterns += ( url(r'^$', static_views.serve, kwargs={'path': 'app/index.html'}), ) What would be analogous to this in 2.0? I assume I'd have to override the "http" in my ProtocolTypeRouter, but unclear how to make that happen. -
How to save with django model form multiple data into one table?
I have a model to save the reservation data with a form model and it works very well but only for one person. I would like that when the number of people exceeds a person the form asks the same data for the following people in the same form with the same model (Table). I have tried to create multiple model to save data depending the number of people but it's not what I want because I want to do this with one model I mean one table from the database. This is my model: class BusTicket(models.Model): ''' Class to define a bus ticket ''' vip_types = ( ('Yes', 'Yes'), ('No', 'No'), ) #each indivitual status PENDING = 'Pending' CONFIRMED = 'Confrimed' TICKET_STATUSES = ((PENDING,'Pending'), (CONFIRMED,'Confrimed'), ) vip_booking = models.CharField(max_length=60, choices=vip_types, default="No") gender = models.CharField(max_length=15, choices=gender_choices) first_name = models.CharField(max_length = 255) last_name = models.CharField(max_length = 255) email = models.EmailField(max_length = 254) active = models.BooleanField(default=True) update = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) bus_id = models.ForeignKey(BusTravels, on_delete=models.CASCADE, blank=True, null=True) phone_number = PhoneNumberField() def __str__(self): return self.first_name + ' ' + self.last_name + ' ' + str(self.phone_number) -
Django OneToOneField allow online one reference
I am trying to create a one to one reference and want to make sure that that reference is not allowed to be used for another model or instance. For example Say I have an address model, Person Model and Company Model Person has a OneToOneField field to Address Company also has a OneToOneField field to Address address=Address(data="some address") company=Company(name="some company",address=address) person=Person(name="my name",address=address) Models: class Address(models.Model): data = models.CharField(max_length=255, blank=True, null=True) class Company(models.Model): name = models.CharField(max_length=255, blank=True, null=True) address=models.OneToOneField(Address,on_delete=models.CASCADE) class Person(models.Model): name = models.CharField(max_length=255, blank=True, null=True) address=models.OneToOneField(Address,on_delete=models.CASCADE) I would like the system to throw an error on this since I am setting the same address to 2 different models. Also this would delete both person and company if I delete address. Usually you catch this with code and not make a stupid mistake like this. But can system catch it since it is one to one ? -
Django bootstrap4 - Parameter "form" should contain a valid Django Form
I am getting the following Bootstrap exception 'Parameter "form" should contain a valid Django Form.' when running the following code from this tutorial: {% load bootstrap4 %} <form action="/url/to/submit/" method="post" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">Submit</button> {% endbuttons %} </form> Is the second'form' in 'bootstrap_form form' supposed to reference/point to something? Is it a variable? What is a valid django form? I checked several posts and answers on this issue, but haven't been able to make sense of this error. -
I am trying to run an endless worker thread (daemon) from within Django
I have a worker thread which only task is to query a list of active users every 10 minutes from the database, and to send them an SMS message if a certain condition is fulfilled (which is checked every minute); also the worker thread does not hinder the main application at all. So far I managed to get the thread up and running and sending SMS works also just fine. However, for some reasons the thread stops/gets killed after some random time (hours). I run a try: except Exception as e: within a while True, to catch occurring errors. Additionally, I print out a messages saying what error occurred. Well, I never see any message and the thread is definitely down. Therefore, I suspect Gunicorn or Django to kill my thread sort of gracefully. I have put log and print statements all over the code but haven't found anything indicating why my thread is getting killed. My wsgi.py function where I call the function to start my thread """ WSGI config for django_web project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application … -
search non index fields in django vs making them keys
This is a general question about searching on a non-indexed field in Django 2.2 If I have a model with class Policy(models.Model): policy_no = models.PositiveIntegerField() eff_date = models.DateTime(auto_now=False, auto_now_add=False) name_id = models.ForeignKey(InsuredName, on_delete=models.CASCADE) Now when the insured goes to my website and searches for his policy number. I do not have this as the primary key because you can have many policies endorsements(change in coverage) during a policy term. There can be millions of policies. Should I use the following model setup instead to add policy number as an indexed field? class Policy(models.Model): policy_no = models.PositiveIntegerField(db_index=True) eff_date = models.DateTime(auto_now=False, auto_now_add=False) name_id = models.ForeignKey(InsuredName, on_delete=models.CASCADE) Also is it a good practice if you are going to order by, or filter by, it should be indexed. Please let me know if this is the correct way to make a field indexed. Thank you I need to know what approach is better? Nonindex field vs indexed class Policy(models.Model): policy_no = models.PositiveIntegerField() eff_date = models.DateTime(auto_now=False, auto_now_add=False) name_id = models.ForeignKey(InsuredName, on_delete=models.CASCADE) vs class Policy(models.Model): policy_no = models.PositiveIntegerField(db_index=True) eff_date = models.DateTime(auto_now=False, auto_now_add=False) name_id = models.ForeignKey(InsuredName, on_delete=models.CASCADE) Also is it a good practice if you are going to order by, or filter by, it should be indexed. … -
Form not raising ValidationError on creation, only when instance is updated
I have kind of a strange error when I try to clean my instance data. My instance is running a clean method to create a condition where the required stock needs to be less than the actual stock. Even so, the method only works when the instance its updated, and not when the instance is created. Another strange behavior is that I have in console the error printing "validation error raised", but the actual error is not raising ONLY when created. I am not very sure if I am triggering the method in a good way. class SaleItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(SaleItemForm, self).__init__(*args, **kwargs) self.fields['client'].queryset = Associate.objects.filter(status="CLIENT") class Meta: model = SaleItem exclude = () # validate clean information def clean(self): cleaned_data = super().clean() print("CLEAN COUNT") product_temp = cleaned_data.get('product') count_temp = cleaned_data.get('count') product_stock = Product.objects.get(id=product_temp.id).stock print("Count:{}".format(count_temp)) print("Stock:{}".format(product_stock)) if count_temp > product_stock: print("validation error raised") self.add_error('count','Not possible to obtain more items than allowed') -
Display profile image in nav bar
I am building my own blog site. I managed to have the users upload their own profile pic and have it displayed beside their post but now i want to have that same image be displayed in the navbar as a profile image but when i do it the same way i did it with the posts it doesnt work and looks like this. For the posts i made a profile image model and accessed the variable from within the html file but the same method does not work for displaying it in the nav bar. I am using python and django for backend. This is my model code for the profile image: from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics") def __str__(self): return f"{self.user.username} Profile" def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) This is how i reference it in my html file for displaying next to posts: <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}" id="img"> What am I doing wrong? -
Mailgun forwarded POST requests have completely another requests data
We have the mailgun setup that forwards the emails to our API endpoint to be scraped. But, nearly 20 per cent of the transactions data is not the data expected, but the data of the some previously failed POST request to our scraping end point. this is the craziest problem I have ever seen, when I open the log file and check the URL of storage field, open the file I see that recipient and content is the one I expected, but when I log it on my endpoint, I see completely different data. I have opened a support ticket but couldn't have a logical response yet. Mailgun forwarding, POSTing emails to scraping API endpoints developed in Django Rest Framework running on Heroku Server response: 404 "error: user not found adfc@blabla.com" which I directly printing from request.POST.get("recipient") field. But the actually file has completely another recipient as well as other request.POST fields -
Django site won't load both http and https links submitted via form/model
Users can submit links to external sites via a form and "Event Website" field on my site. The site is sent to the "link" model in the admin and is rendered in the template with <a href="//{{ item.link }}" target="_blank"> {{ item.title }} </a>. However, not all links are loading the external site. When on the production site, only links with "http://" or "https://" included in the link the user submitted navigate to the external site. Links entered without such as "facebook.com" or "www.facebook.com" do not load. I get a 404 error. How can I get my page to load the external site no matter how the link is entered (given that it's valid)? -
How to sort values of serializer custom field in DRF
I have created a custom field in the client serializer. The value of this field is calculated by a complex serializer method. class ClientStatsSerializer(serializers.ModelSerializer): """ Serializer shows total_spend for 2019 by client. """ refs_count = serializers.SerializerMethodField() total_spend_2019 = serializers.SerializerMethodField() class Meta: model = Company ordering = ('total_spend_2019',) fields = [ 'id', 'legal_name', 'refs_count', 'total_spend_2019', ] def get_total_spend_2019(self, obj): ... I would like to get the output sorted by the value of total_spend_2019. It looks like I cannot do it here with a simple ordering = ('total_spend_2019',) I cannot do it either in the model, neither in the view. Any idea how to solve this? Thank you very much!! -
Loading data through template rendering?
Currently I have some code in my index.html looking like: <script> var episodes = [ {% for episode in episodes_json %} {{episode|safe}}, {% endfor %} ] </script> And in my view: def view(request): return render("index.html", request, {"episodes": ...} This loads some data that I display to my user. It works great, but I haven't seen this type of data loading in any django tutorials I've seen thus far. Are there are any downfalls to loading data this way, rather than through AJAX request or something?