Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy django with kubernetes ingress
I am unable to setup path for django application form kubernetes nginx. The application is running fine on local development but not with kubernetes. It says Failed to connect Minimal reproduceable example <values.yaml> imageName: ingestion-dashboard replicas: 1 ingressAnnotations: nginx.ingress.kubernetes.io/use-regex: "true" ingressRules: - path: /dashboard portName: http <deployment.yaml> {{ include "ingestion-dashboard.deployment-header" . }} spec: {{ include "ingestion-dashboard.workerNodeSelector" . | indent 6 }} containers: - name: ingestion-dashboard {{ include "image" . | nindent 10 }} env: - name: SOME_ENV value: SOME_VAL ports: - containerPort: 4781 hostIP: 0.0.0.0 <service.yaml> apiVersion: v1 kind: Service metadata: name: ingestion-dashboard labels: {{ include "ingestion-dashboard.labels" . | indent 4 }} spec: ports: - name: http port: 4781 protocol: TCP targetPort: 4781 selector: app.kubernetes.io/name: {{ include "ingestion-dashboard.name" . }} app.kubernetes.io/instance: {{ .Release.Name }} <urls.py> {in django} urlpatterns = [ path('/dashboard/', include(running_urls.urlpatterns)) ] Port `4781` is configured everywhere (docker file as well) below is the output of k get service ingestion-dashboard -o wide NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE ingestion-dashboard ClusterIP 10.69.37.77 <none> 4781/TCP 13h This is not working. The same setup runs fine when used for flask app. But this is not running for django. Nginx and django apps have no errors as Nginx is running fine for others(including … -
I am trying to view and download a file that I have uploaded using django web application. The web does not open when clicking on view or download
Here is my HTML home.html template. <a href="{{MEDIA_URL}}/{{post.file_field.url}}" class="btn btn-warning" target="_blank">View</a> <a href="{{MEDIA_URL}}/{{post.file_field.url}}" class="btn btn-info mx-4" download>Download</a> settings.py MEDIA_ROOT = BASE_DIR / 'media/' MEDIA_URL = 'media/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('photoapp.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to get an object's id and use it for child's query?
def customer(request, customer_id): """Displays customer profile""" customer = Customer.objects.get(id=customer_id) entries = customer.entry_set.order_by('-date_added') subentry = SubEntry.objects.get() context = {'customer': customer, 'entries': entries, 'subentry': subentry} return render(request, 'crm/customer.html', context) I have three classes, Customer, Entry and SubEntry. Customer is a ForeignKey to Entry and Entry is a ForeignKey to SubEntry. Each class has a textfield whose id I can access through the python shell. Currently, I have customer.html displaying a loop that iterates through the entries for a customer. Is there are better way to show this information and print out the subentry for each entry? -
How to redirect to same page after posting in django?
In my django application, I have a form that redirects to a new page if the form is valid. On that new page, I want to include a new form where I can add time slots. How can I set my function in views.py so I can redirect to the same page after inputing the start_time and end_time for the timeslot? This is what I have so far: In models.py class TimeSlot(models.Model): time_slot_owner = models.ForeignKey(User, on_delete=models.CASCADE) food_avail_id = models.ForeignKey(FoodAvail, on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() def __str__(self): return str(self.start_time) + "-" + str(self.end_time) In forms.py: class TimeSlotForm(ModelForm): class Meta: model = TimeSlot fields = ["start_time", "end_time"] In views.py: def create_timeslots(request): if not check_existing_timeslot(request): instance = TimeSlot() data = request.POST.copy() data["time_slot_owner"] = request.user data["food_avail_id"] = FoodAvail.objects.get(author=request.user) form = TimeSlotForm(data or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) else: instance = get_object_or_404(TimeSlot, time_slot_owner=request.user) form = TimeSlotForm(request.POST, request.FILES, instance=instance) if request.method == "POST": form = TimeSlotForm(request.POST or None, instance=instance) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) else: form = TimeSlotForm(instance=instance) return render(request, "food_avail/view_food_avail.html", {"timeslot": form}) My HTML template: {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> {{ field.label }} <strong>{{ error|escape … -
How to have a two parallel ListViews for near identical CreateView views in Django
I have the following Django code. models.py class Article(models.Model): title = models.CharField(max_length=255) #Body is the "body" of our entry - self explanatory. comment = models.TextField() views.py class ArticleListView(ListView): model = Article paginate_by = 50 fields = ('title', 'comment') template_name = 'article_list.html' class ArticleCreateView(CreateView): model = Article template_name = 'article_new.html' fields = ('title', 'comment') I simplified (removed unecessary details from the code) the code, as there are DetailViews and UpdateViews which are pretty standard. What I would like to do is add something like the following to my views.py class ArticleListView2(ListView): model = Article paginate_by = 50 fields = ('title', 'comment') template_name = 'article_list.html' class ArticleCreateView2(CreateView): model = Article template_name = 'article_new.html' fields = ('title', 'comment') Whereby the ArticleCreateView2 looks identical to the ArticleCreateView except instead of the article getting added to ArticleListView it would get added to ArticleListView2 and when I get to ArticleListView2 I could use an UpdateView feature which after updating would "move" the article to the "original" ArticleListView. Is there any way I can do this simply? Thank you. -
Django: filter by user and Primary Key
in my app the Week model is linked thanks to a OneToOneField to the File model and I'd like to get only the file uploaded by the user themselves and to use all the values in the same model to create a chart. So if User_A post file_id_one (monday=3, tuesday=7 [...]) and file_id_two (monday=4, tuesday=9 [...])I'd like to filter and get only the file posted by the logged in User_A and when the user reach The data.html using a pk "{% url 'data' data.id %}" a chart with the value of file_id_one (monday=3, tuesday=7 [...]) will appear if the pk is 1. if the pk is two then a chart with file_id_two (monday=4, tuesday=9 [...]). So I think I need to filter by user and also by pk? Right now with my code this is the error I'm getting 'WSGIRequest' object has no attribute 'file' . However colors = File.objects.filter(pk=pk) it's actualy working but if I use data = list(Week.objects.filter(pk=pk)[2:] the data variable is blank. MODEL class File(models.Model): user = models.ForeignKey(UserData, on_delete=models.CASCADE) docfile = models.FileField(upload_to=path) color = models.CharField(max_length=250) class Week(models.Model): file_doc = models.OneToOneField(File, on_delete=models.CASCADE) monday = models.PositiveIntegerField(null=True) tuesday = models.PositiveIntegerField(null=True) wednesday = models.PositiveIntegerField(null=True) thursday = models.PositiveIntegerField(null=True) friday = models.PositiveIntegerField(null=True) saturday … -
Django restframework viewset serializer KeyError
I try to POST request but I got KeyError. Exception Location: C:\github\dj-postgres-heroku\get_staff\serializers.py, line 32, in create Here is error location and that line is this. def create(self, validated_data): **profile_data = validated_data.pop('profile')** I try to POST data like this. enter image description here enter image description here { "profile":1, "title": "일단 10만원, 업무 마친 후 바로 입금", "hourly_pay": 12500, "start_date": "2020-05-06", "end_date": "2020-05-09", "start_time": "09:00:00", "end_time": "18:00:00", "content": "간단업무입니다.", "jobs":[1, 2] } Here are my code all. models.py class GetStaffPost(models.Model): profile = models.ForeignKey(Profile, null=True, on_delete=models.CASCADE) # default=1 -> pk=1 title = models.CharField(max_length=30) jobs = models.ManyToManyField(Job, blank=True) # tag랑 비슷 hourly_pay = models.IntegerField(null=True) start_date = models.DateField(null=True) end_date = models.DateField(null=True) start_time = models.TimeField(null=True) end_time = models.TimeField(null=True) created_at = models.DateTimeField(null=True, auto_now_add=True) content = models.TextField(default='content') class Meta: ordering = ['-created_at'] def __str__(self): return f'{self.pk}: {self.title} - {self.profile.nickname}' serializers.py class GetStaffPostSerializer(serializers.ModelSerializer): profile = serializers.PrimaryKeyRelatedField(read_only=True) jobs = serializers.PrimaryKeyRelatedField(read_only=True, many=True) class Meta: model = GetStaffPost # fields = ['id', 'profile', 'title', 'jobs', 'hourly_pay', 'start_date', 'end_date', # 'start_time', 'end_time', 'created_at', 'content'] fields = "__all__" def create(self, validated_data): # profile, jobs profile_data = validated_data.pop('profile') profile_id = profile_data profile = Profile.objects.get(pk=profile_id) jobs_data = validated_data.pop('jobs') # list? post = GetStaffPost.objects.create(**validated_data, profile=profile) # Direct assignment to the forward side of a many-to-many set … -
How do i run django application without port number
How do i run django application without port number: i had tried Django: Run django app on server without port? but didn't work. -
Django Heroku Migrate Error(?): "You have 21 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s)"
So I'm working on hosting a project and on my Heroku dashboard it says it's live, but every time I try to access it I get a 500 Server Error, even when trying to access it locally via Heroku CLI. I tried running migrations because I get the following warning: You have 21 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, recipe, sessions, users. Run 'python manage.py migrate' to apply them. Even after running makemigrations and migrate, as can be seen in screenshot below, any suggestions to what I might be missing? -
How to query multiple models in the same query in Django?
This is the SQL query I have been trying to convert to Django but I cannot figure out how to query multiple models together. FROM EMPLOYEE,DEPARTMENT,PERSON WHERE EMPLOYEE.ID = :ID and PERSON.ID = EMPLOYEE.ID and EMPLOYEE.UNIT = DEPARTMENT.UNIT``` -
Chart.js with degrees
I'm trying to chart some data on a graph where the x axis is azimuth (degrees) and the y axis is elevation (degrees). I'm not exactly sure what the problem is, but I'm guessing it has something to do with my data range trying to wrap from 359 degrees to 20 degrees When there is no wrap around, the chart looks fine with data like this: https://ibb.co/9TX5p5G Zone Az Start Az Stop Elevation 1 0 359 1.7 2 173 197 9.6 3 206 216 3.2 4 217 300 3.7 5 341 351 4.6 However, when I use data that wraps around 360 degrees like this (see zone 2), the graph does not display properly Zone Az Start Az Stop Elevation 1 0 359 1.3 2 359 20 6.4 3 28 43 5.5 4 288 302 5.5 5 351 354 2.8 StackOverflow won't let me post the images of the graphs, but here is my code: https://ibb.co/kxn5mqm views.py def data_tiz(request): # Get the current URL we are on (it says what site we want TIZ data for) tiz_site = request.path.split('/')[3] current_day = datetime.now() # Gather all TIZ objects that live in the DB all_tiz_values = Tiz.objects.all() # Initiate empty arrays tiz_to_display … -
Write a function to reduce duplicate code
I have two very similar for loops, I want to have an inner function to reduce the duplicate codes, they look like this: team_members = TeamMember.objects.all() managers = Manager.objects.all() for m in managers: name = f"{m.name.first_name} {m.name.last_name}" //reset of the code are the same for t in team_members: name = f"{t.member.first_name} {t.member.last_name}" //reset of the code are the same So the problem is managers and team_members querysets have different field names for people's names. If I want to write an inner function, how to solve the different field names? -
How to display images in Django questionnaire
I am working on a Django app where the user will be able to take any survey they pick from a list of surveys. For one of the surveys, they are supposed to select an image that best represents their mood. For their answer I do not need to record the image they selected, just the name of the mood it represents (for example, "cheerful"). Therefore, I have not yet added an "image" field to the model. However, the user should be able to see the image and select it. At the moment I am not able to display the images, only getting the names. I have checked my code and still unable to find the mistake. By the way, not getting any technical error messages. Any recommendations you have are appreciated. Below are my models, views, and HTML. I apologize for the lengthy files. Thank you! Models User = settings.AUTH_USER_MODEL class Questionnaire(models.Model): name = models.CharField(max_length=255) text = models.CharField(max_length=200) def __str__(self): return self.name class Question(models.Model): text = models.CharField(max_length=200) questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE, related_name='questions') def __str__(self): return self.text class Answer(models.Model): questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE, related_name='answers', default='') text = models.CharField(max_length=200) def __str__(self): return self.text class Response(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) … -
The best approach to keep API views and Template views in Django
I'm looking for the best approach/practice to keep API views and Template views in Django. Making a separate app called API/ or keeping all views together in the views.py file? There is also another approach that creates a directory within the main app called views/ which includes views/api.py and views/visual.py and simply removes the traditional views.py. Which is better?? -
Django how can i solve the problem with objects.all()?
Could someone help me. After starting . I do not have any data submitted to the chart. I am not getting any errors. I am trying to solve it but I have no idea anymore. in the view.py file I have: def index(request): data = Chartdata.objects.all() context = { 'data': data, } return render(request,'dashboard/home.html', context) in the models.py file I have: from django.db import models class Chartdata(models.Model): name = models.CharField(max_length=100) numberone = models.IntegerField() html file: <div class="charts"> <canvas id="myChart" width="400" height="200"></canvas> <script> const ctx = document.getElementById('myChart'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: [{{ data.name }},], datasets: [{ label: '# of Votes', data: [{{ data.numberone }},], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', ], borderWidth: 5 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </div> -
How can I apply bootstrap to my whole django project?
I've been looking at a few guides on applying bootsrap to django, and I am as far as having a static file in the root of my site, containing the css and js files within bootstrap, but when it comes to linking the files I am having an issue. So I am trying to link the stylesheet inside of my base.html file but am not sure how to format it as for some reason using {% %} inside of the href field is being interpreted as part of the directory. In one of the videos I have watched he links it like thisBut I'm not really sure how to interpret this as trying to apply it to my own like so href = "{% static 'artForAll/css/bootstrap.css%" With the file structure for reference: \AFA\src\artForAll\static\artForAll\css I am given an error about a non existent file as it is taking the {%%} as part of the directory -
How to populate Django database in migration with CreateUserForm
I'm working on an app that has a set of Users created from the CreateUserForm in my forms.py. In my models.py I have an Account that links to that user created in the form. Everything works great except for when I perform a migration I want it to create a new user and create a new account for that user. I keep getting a NOT NULL constraint failed: auth_user.last_login exception. Any help would be AMAZING!! forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] models.py from typing import DefaultDict 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 from decimal import Decimal # Create your models here. class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) balance = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) userType = models.IntegerField(default=1) #1 = Player, 2 = Sponsor, 3 = Bartender, 4 = Manager, 5 = Admin currentHole = models.IntegerField(default=0) triedToSponsor = models.BooleanField(default=False) @receiver(post_save, sender=User) def create_account(sender, instance, created, **kwargs): if created: Account.objects.create(user=instance, balance=0.00, userType=1) @receiver(post_save, sender=User) def save_account(sender, instance, **kwargs): instance.account.save() def __str__(self): return str(self.user.username) + " has $" + str(self.balance) + " userType: " + str(self.userType) + " id: " … -
Obtain the country from IPs in a text file
I'm trying to obtain the country for each IP in a text file I have the code for obtain the country from the IP (manually) and the code for extract the IP from my txt file but now I don't know how to obtain the country for each IP and after that put the result in a new column in SQL Server. I hope someone can help me. ---------------geoip code---------------- from django.http import response import pygeoip try: gi = pygeoip.GeoIP('C:/Users/Damian.Flores/OneDrive - Interpublic/Documents/GeoLiteCity.dat') def printRecord(ip): rec = gi.record_by_name(ip) city = rec['city'] country = rec['country_name'] print('Address: ' + ip) print(str(city)+ ', '+str(country)) ip=('10.0.0.12') printRecord(ip) except Exception: print("IP Privada") -------------------------ips from txt file-------------------------------- import re with open('C:/Users/Damian.Flores/OneDrive - Interpublic/Documents/pruebas/intranet-access_log1.txt') as fh: fstring = fh.readlines() pattern = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})') lst=[] for line in fstring: lst.append(pattern.search(line)[0]) print(lst) -
Call stored procedure in Django
I am trying to call a stored procedure in Django that returns some data based on which batch number you give it. In my database if I write call InkItUp.InkBatchNumberCallBackk(15137); I return the data I need. But then I try to use Postman to call the URL I have defined for the view saveInkbatch in my urls.py file It gives me this error: The view api.views.saveInkbatch didn't return an HttpResponse object. It returned None instead. Me urls.py look something like this: path('createsp/', views.saveInkbatch), and there is the method in the view.py @csrf_exempt def saveInkbatch(request): if request.method == 'POST': if request.POST.get('batchnumber'): save=Ink() save.batchnumber=request.POST.get('batchnumber') cursor=connection.cursor() cursor.execute("call InkItUp.InkBatchNumberCallBackk('"+save.batchnumber+"')") messages.success(request, "The batchnumber "+save.batchnumber+"") return HttpResponse(request, content_type = 'application/json') If you know a way to call a stored procedure from MySQl with a class-based view - It would be nice to. I would much rather use class-based views if possibly. -
How can I tell Django Graphene Relay to return the default connection type for a custom resolver?
I have Django models that contain an M2M relationship like this: class ColorLibrary(BaseModel): {..properties..} class Account(BaseModel): color_libraries = ManyToManyField("ColorLibrary", etc...) I have a Relay node like this: class ColorLibraryNode(ObjectType): class Meta: model = ColorLibrary interfaces = (graphene.relay.Node,) Then Relay will automatically resolve Account.color_libraries with a ColorLibraryNodeConnection type that contains the edges/node syntax for querying the color libraries. The problem I'm having is I also have some circumstances where I need a custom resolver for ColorLibrary objects, for example I would like to get the default library for an account, which I define like this: default_color_library = graphene.Field(ColorLibraryNode) def resolve_default_color_library(parent, info): {..code..} This creates an inconvenience client-side as the returned type is ColorLibraryNode instead of ColorLibraryNodeConnection, so I'm not able to use the same fragments (and I lose the edges/node syntax). How can I create a custom resolver but utilize the built-in default connection class that's created? I want to have something like this instead: default_color_library = graphene.relay.ConnectionField(ColorLibraryNodeConnection) But the problem is ColorLibraryNodeConnection isn't defined anywhere. If I attempt to create a custom connection class of the same name, I get a conflicting name exception as it builds the schema. If I use a custom type here, then I also have … -
Filter foreign key data entered by a user in a Django form
I have this Model that has a foreign Key. I want anytime a user if filling the form, Only the data entered by the user in the foreign key model should be shown to him as a dropdown. Model.py class Nomination(models.Model): fullname = models.CharField(max_length=120) nominee_id = models.CharField(max_length=100, default=increment_invoice_number, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to='nominations_images') slug = models.SlugField(max_length=150, blank=True) votes = models.IntegerField(default=0, blank=True) date = models.DateTimeField(auto_now_add=True) createdby = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) forms.py class CategoryForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CategoryForm, self).__init__(*args, **kwargs) # access object through self.instance... self.fields['createdby'].queryset = Award.objects.filter(createdby=self.instance.user) class Meta: model = Category fields = "__all__" This is the error I get. 'Nomination' object has no attribute 'user' -
Django blog app won't display edit posts page
Currently working through the Python Crash Course Django section I've got everything but the edit posts page working. When you click on it the NoReverseMatch error displays with this message: Reverse for 'edit_post' with no arguments not found. 1 pattern(s) tried: ['edit_post/(?P<post_id>[0-9]+)/$'] Here is the code I've been using. from django.db import models # Create your models here. class BlogPost(models.Model): """A topic the user is learning about""" title = models.CharField(max_length=200) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """A place for the user to create a blog post""" return self.title Views from django.shortcuts import render, redirect from .models import BlogPost from .forms import BlogForm # Create your views here. def index(request): """The home page for Blog""" return render(request, 'blogs/index.html') def blogposts(request): """Show all blogposts""" blogposts = BlogPost.objects.order_by('date_added') context = {'blogposts': blogposts} return render(request, 'blogs/blogposts.html', context) def new_post(request): """Add a new post""" if request.method != 'POST': # No data submitted, create a blank form form = BlogForm() else: # POST data submitted; process data form = BlogForm(data=request.POST) if form.is_valid(): form.save() return redirect('blogs:blogposts') # Display a blank or invalid form context = {'form': form} return render(request, 'blogs/new_post.html', context) def edit_post(request, post_id): current_entry = BlogPost.objects.get(id=post_id) if request.method != 'POST': # Initial request; pre-fill … -
How a (python) web application is deployed?
Sorry but I have a dumb question. How a (python coded) web application is deployed in a server so the clients can use it ? And also, if, me, I need to install python packages (pandas, django,.. ) so I can create my web application in an IDE, how can the clients use my app without the need of doing the same (I mean, installing the same packages in their computers) ? Thank you so much ! Rgds, M92 -
How to log the start of the server
I would like to generate a log message once, when the server starts. I.e. once after "runserver". Where shall I place the log.info statement? -
Is there a professional way to plan your REST API?
I am planning out a Skill marketplace, I am using Python Django REST API, I want to know if there's a professional way to design a API to be consumed by multiple frontend. This is my first time of designing an API (though I have done multiple small projects). Any links, guide would be greatly appreciated.