Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django Rest Framework is_valid returns no error
I'm trying to implement Google social login, I verify TokenID I get from the frontend and here is what I'm getting: {'iss': 'accounts.google.com', 'azp': '{SomeData}', 'aud': '{SomeData}', 'sub': '107380020022573036077', 'email': '{SomeData}', 'email_verified': True, 'at_hash': 'Nu2TdaoGnS5t1MomTRdmKw', 'name': '{SomeData}', 'picture': '{SomeData}', 'given_name': '{SomeData}', 'family_name': '{SomeData}', 'locale': 'en', 'iat': 1637094558, 'exp': 1637098158, 'jti': '{SomeData}'} I need the email, first_name, password to register the account, here is the model: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): public_api = models.TextField(default=None, null=True) secret_api = models.TextField(default=None, null=True) market = models.TextField(default=None, null=True) email = models.EmailField(unique=True) first_name = models.CharField(max_length=150) last_name = models.CharField( max_length=150) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] Here is the serializer: from rest_framework import serializers from django.contrib.auth import get_user_model class RegisterSerializer(serializers.ModelSerializer): first_name = serializers.CharField(source='given_name') last_name = serializers.CharField(source='family_name') email = serializers.CharField(required=True) class Meta: model = get_user_model() fields=['email', 'first_name', 'last_name'] Here is the view: class GoogleLogin(APIView): permission_classes = [AllowAny] def post(self, request): data = request.data token = data['access_token'] token_info = id_token.verify_oauth2_token(token, requests.Request(), '') serializer = RegisterSerializer(data=token_info) serializer.is_valid(raise_exception=True) serializer.save() return Response('Success') And all I'm getting in the console is this message: Bad Request: /auth/google [17/Nov/2021 00:36:24] "POST /auth/google HTTP/1.1" 400 82 -
Should I make requests to this API/change the structure of this API/use a DB instead?
That's what my Django Rest Framework API looks like. I want to use information from it on my website(where users can search for a flight and they will see the appropriate results). Of course I can filter the API in many ways, but the problem is I don't know what to do when it comes to searching for indirect flights. I also don't know what functions to use. I've already used fetch to create autocomplete but that's a different situation. Can fetch be used here too? Or maybe I should create the API in another way? And of course there's an option of using a db, the easiest one for me, but I would prefer using API. Maybe that's a dumb question, but I'm just confused -
In django, how do I return the other end of a many to many join?
I have a table schema like this. You're a user and you want to get the list of your other users (as User models). I've got a known users.id value. The SQL for this query is relatively straightforward: join users_B = entries_B.your_user and entries_B.other_user = users_B.id where entries_B.your_user = x. I can't figure out how to do this in django unless I post process the data (using prefetch_related counts as post processing) or generate a really weird query (something involving left joins and subqueries). Is there a way to get a list of Users back and have the generated SQL be straightforward and concise? -
How to integrate Cognito SSO with Django grapehene
We have an up and running django project that already uses graphene and graphql_jwt (along with django's internal auth). We are attempting to integrate SSO with cognito for this project, but since graphene and graphql_jwt already have their inbuilt auth mechanisms, its becoming hard to make sense of how to integrate Cognito with these. My guess was that I will mostly be needing to only add an authentication backend, that sets the user using the cognito. But this is causing issues with the graphql's existing authentication and it is unable to recognise that the user has already been authenticated. How can the cognito's authentication be added to the existing graphql_jwt flow? -
How do I change the value of true or false to a text value type it I am checking the row in the entire table Note the table is of type datatables?
use django How do I change the value of true or false to a text value type it I am checking the row in the entire table name item type items active item1 15.0 True item2 15.0 False change values row active use jquery or django file view.py: name item type items active item1 15.0 displayed item2 15.0 stope help please -
In Django, how do I construct my queryset to filter by time over slices of time?
I'm using Python 3.9 and Django 3.2. I have this price model class Price(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) price = models.FloatField(null=False) created = models.DateTimeField(null=False, default=datetime.now) If I want to get the price per hour over the last 24 hours, I can run a method like this def _get_prices_per_time_slice(self, last_hours=24): now = timezone.now() end_time = now.replace(second = 0, microsecond = 0) start_time = end_time - timedelta(hours=last_hours) qset = Price.objects.filter( created__range=[start_time, end_time], created__minute=end_time.minute ).values('price') return [r['price'] for r in qset] but let's say I want to get the price every last X hours. def _get_prices_per_time_slice(self, last_hours=24, time_slice_in_hours=4): so if the current time is midnight (and zero seconds and minutes), I would want to get the prices for midnight, 8 pm, 4 pm, noon, 8 am and 4 am. How do I add a filter to screen for prices every X hours? -
Django form/formset button to add field
models.py class Car(models.Model): FUEL = ( ('', '---------'), ('1', 'Gasoline'), ('2', 'Diesel'), ('3', 'Electric'), ('4', 'Hybrid'), ) client = models.ForeignKey(Client,on_delete=models.CASCADE, null=True, blank=True) car_make = models.ForeignKey(CarMake, on_delete=models.CASCADE) car_model = models.ForeignKey(CarModel, on_delete=CASCADE) fuel_type = models.CharField(max_length=15, choices=FUEL, default=None) engine = models.CharField(max_length=15) service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, blank=True) extra_info = models.TextField(max_length=300, verbose_name='Info.', null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) forms.py CarFormset = modelformset_factory( models.Car, fields=('service', ), extra=1, widgets={'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Whatever' }) } ) class CarForm(forms.ModelForm): class Meta: model = models.Car fields = '__all__' template {% load crispy_forms_tags %} <form action='' method='post'> {% csrf_token %} {{ form|crispy }} <input type='submit' value='Submit'> {% if formset %} {{formset.management_form}} <div id='service-form-test'></div> <div id='empty-form' class=''>{{formset.empty_form}}</div> <button id='add-more' type='button'>Add</button> {% endif %} </form> <script> const addMoreBtn = document.getElementById('add-more') const totalNewForms = document.getElementById('id_form-TOTAL_FORMS') const currentServiceForms = document.getElementsByClassName('service-form') addMoreBtn.addEventListener('click', add_new_form) function add_new_form(event) { if (event) { event.preventDefault() } const currentFormCount = currentServiceForms.length // + 1 console.log(currentServiceForms.length) const formCopyTarget = document.getElementById('service-form-test') const copyEmptyFormEl = document.getElementById('empty-form').cloneNode(true) copyEmptyFormEl.setAttribute('class', 'service-form') copyEmptyFormEl.setAttribute('id', `form-${currentFormCount}`) const regex = new RegExp('__prefix__', 'g') copyEmptyFormEl.innerHTML = copyEmptyFormEl.innerHTML.replace(regex, currentFormCount) totalNewForms.setAttribute('value', currentFormCount + 1) formCopyTarget.append(copyEmptyFormEl) } </script> Hello, i will add an image of what im trying to do, im a beginner and the only place that i can ask … -
How send confirmation email when user perform register method twice?
In register class I wrote method that raise_exception is true and check email must be unique because I used jwt authentication with email. When user perform this method for one time ,he get email confirmation .if user don't confirm and run register method for second time .he occure error email is registered. Because this email for one time has been registered in data base. How can I handle this issue? -
ModuleNotFoundError: No module named 'django_user_agents'
I am using this library to understand if user is coming from PC or mobile but I am getting this error ModuleNotFoundError: No module named 'django_user_agents'.Anyone know the solution for this problem ? I am using Django 3 +. -
Run javascript in each Django for loop?
I have a Javascript function that converts markdown to html: <script> $(function () { editormd.markdownToHTML("content", { //htmlDecode : "style,script,iframe", // you can filter tags decode emoji : true, taskList : true, tex : true, flowChart : true, sequenceDiagram : true, }); $(".reference-link").each(function (i,obj) { console.log(obj) }) }) </script> But when I run this in a for loop the Javascript only runs on the first post. {% for entry in entry_list %} <div id="content"><textarea>{{ entry.content|truncatechars_html:180 }}</textarea></div> {% endfor %} How do I make it run on each loop? -
stay in the same tab after refreshing page
I have a page which contains same url but a lot of tabs after I click on a tab I can see its content but right after I refresh the page tab(0) appear but I want the last used tab. how can I do that. this is the js code <script> const tabBtn = document.querySelectorAll(".tab"); const tab = document.querySelectorAll(".tabShow"); function tabs(panelIndex){ tab.forEach(function(node){ node.style.display="none"; }); tab[panelIndex].style.display="block"; } tabs(0); $(".tab").click(function(){ $(this).addClass("active").siblings().removeClass("active"); }); </script> -
How to get django form to accept a disabled form with intial values
What I'm trying to do is to allow Django to accept a form that's been disabled using form.disabled. When I try to submit it, however, the initial value that's been calculated on the server seems to disappear into the wind, even though the Django documentation seems to imply that it should be doing otherwise. forms.py class SubmitResponseForm(forms.Form): response_text = forms.CharField(label='Choice text', max_length=50) main_text = forms.CharField(label='Main text', max_length=5000) class SubmitResponseLiteForm(forms.Form): response_text = forms.CharField(label='Choice text', max_length=50) main_text = forms.CharField(label='Main text', max_length=5000, disabled=True) views.py #Some unimportant stuff before this if has_role(request.user, 'subscriber'): form = SubmitResponseForm(initial={ 'response_text': split_strings1, 'main_text': split_strings2, }) else: form = SubmitResponseLiteForm(initial={ 'response_text': split_strings1, 'main_text': split_strings2, }) return render(request, 'nodemanager/detail.html', { 'node': node, 'editchoiceform': form }) def SubmitGeneration(request, pk): node = get_object_or_404(Node, pk=pk) time = timezone.now() if has_role(request.user, 'subscriber') == False: form = SubmitResponseLiteForm(request.POST) else: form = SubmitResponseForm(request.POST) if form.is_valid(): main_text = form.cleaned_data['main_text'] response_text = form.cleaned_data['response_text'] node.children.create(main_text=main_text, response_text=response_text, pub_date=time, creator=request.user) return redirect('nodemanager:detail', pk=node.id) else: return render(request, 'nodemanager/detail.html', { 'node': node, 'editchoiceform': form }) -
Python ModuleNotFoundError on pyphen?
This project is Django web application and it has some custom script running and when web app asks for it. Here's the folder structure, And i'm calling the main method of freq_rank_score.py from webapp->views.py. And getting this error, File "C:\Users\pathum\Documents\alteducation_web\word_processor\freq_rank_score.py", line 5, in <module> import pyphen ModuleNotFoundError: No module named 'pyphen' It worked fine when running it outside django project. I have no idea why ? -
want to use email field as a username field for users, vendors but for django-admin I want to use username field as usual
models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.fields import EmailField class CustomUser(AbstractUser): email = models.EmailField(('email address'), unique=True) mobileno = models.IntegerField(blank=True, null=True) is_customer = models.BooleanField(default=False) is_vendor = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class VendorDetails(models.Model): vendoruser = models.OneToOneField(CustomUser, on_delete=models.CASCADE) aadhar_number = models.CharField(max_length=200) pan_number = models.CharField(max_length=200) store_name = models.CharField(max_length=200) brand_name = models.CharField(max_length=200) admin.py from django.contrib import admin from customer.models import CustomUser, VendorDetails # Register your models here. admin.site.register(CustomUser) admin.site.register(VendorDetails) when attempting ----- python manage.py createsuperuser----(File "D:\Yabesh\Django\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username') need help. Thanks in advance. -
In Django how to get specific user's data stored in profiles module
I am working on a project where I need to get some data into a chart but I don't know how to get the only data belongs to a specific user. I am the Using original user modell that I extended with a Profile modell. I'm storing in the Profile a column called "csoport". I like to write a query where I get some other data from my "Kapcsolodasok" modell that joined to Profile modell. I'm not so experienced in Django ORM so I'm using raw query. HTML (just the query part) {% for k in kapcsolodasok %} { id: "{{ k.user.get_full_name }}", label: "{{ k.user.get_full_name }}", group:{% for cs in csoport %}{{ cs.csoport }}{% endfor %} }, {% endfor %} models.py class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) projekt = models.ForeignKey(Projekt, on_delete=models.CASCADE, default=1) csoport = models.CharField(max_length=100) class Kapcsolodasok(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) kap_bar_01 = models.TextField(max_length=200) kap_bar_02 = models.TextField(max_length=200) ... class Projekt(models.Model): def __str__(self): return str(self.projekt) projekt = models.TextField(max_length=150) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) views.py @login_required def project_details_report(request, projekt_id): csoport = Profile.objects.raw('SELECT stressz_profile.projekt_id, stressz_profile.id, stressz_profile.id FROM stressz_profile INNER JOIN stressz_projekt ON …