Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Call variable on input user text
I have a excel data with multiple colums, inside the I have a name colum, now by HTML input the user can write a custom text. I need that the user can use something to call name variable when he like. If use f'User cutsom text {name}' or something like that not work, django keep input user text like a text. Do you know a possibility. I need that the user can use or call variables from the excel when he write his text -
creating new database entrys in django
i am new to django and i am currently setting up a new django app with an existing postgres db. fetching existing data from the database works fine but creating new entries in this database does not work. i have a javascript which sends json data to a view in django. i can access the data in the view but django models.create() and save() seem to do nothing and i dont know why. heres my code: **views.py** from django.shortcuts import render, redirect from django.http import HttpResponse, JsonResponse from notes.models import Profiledata from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def add_events(request): try: if request.method == 'POST': data = json.loads(request.body) print(data) occasion = data['occasion'] year = data['year'] month = data['month'] day = data['day'] print(occasion, day, year, month) new_note = Profiledata(notes = occasion, year = year, month = month, day = day) #print(new_note) new_note.save(force_insert=True) return redirect('') except Exception as e: return JsonResponse({"error": str(e)}) **models.py** class Profiledata(models.Model): id = models.IntegerField(primary_key=True) notes = models.CharField(max_length=500, blank=True, null=True) year = models.IntegerField(blank=True, null=True) month = models.IntegerField(blank=True, null=True) day = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'profiledata' the models.py is created with inspectdb does any one know what i am doing wrong? i tired new_note = … -
Can't set postgresql foreign key using django between two tables
Trying to find out the best way to model my data. I have one table for pokemon types: class PokemonTypesTest2(models.Model): name = models.CharField(max_length=25, unique=True) It just has an ID and name, it will have 18 rows in it. I want to be able to relate multiple tables to it, for example base Pokemon model below ( i cleared out most of the data to be easier to follow: class BasePokemonTest2(models.Model): #other data hidden # type1 = models.ForeignKey(PokemonTypesTest2, on_delete=models.CASCADE, default=1) type2 = models.ForeignKey(PokemonTypesTest2, on_delete=models.CASCADE, default=1) type3 = models.ForeignKey(PokemonTypesTest2, on_delete=models.CASCADE, default=1) weaknessResistanceImmune = models.ManyToManyField(PokemonTypesTest2, through='WeakResistImmune2') I want to be able to relate a pokemon typing to a pokemon from base pokemon table. The problem is I get this error from Django: ERRORS: battlefield.BasePokemonTest2.type1: (fields.E304) Reverse accessor 'PokemonTypesTest2.basepokemontest2_set' for 'battlefield.BasePokemonTest2.type1' clashes with reverse accessor for 'battlefield.BasePokemonTest2.type2'. HINT: Add or change a related_name argument to the definition for 'battlefield.BasePokemonTest2.type1' or 'battlefield.BasePokemonTest2.type2'. I see the hint but don't understand what it means? -
How to fetch data from database with django
Im trying to fetch data from django database. I want to display all the data as divs with different titles, images and description. views.py from .models import Links def all_links(request): links= Links.objects.all() return render(request, 'links.html', {'links' : links}) models.py class Links(models.Model): title = models.CharField(max_length = 30) desc = models.CharField(max_length = 30) link_redirect = models.CharField(max_length = 100) img = models.ImageField(upload_to = None,height_field=None, width_field=None, max_length=100) def __str__(self): return self.title output file: {% for link in link_list %} <div class="links--flex flex"> <div class="links--flex__link"> <div class="link__img"> <img src={% static '/img/links/Pexels.png' %} alt=""> </div> <div class="link__title"> <h2 class='colored'>{{link.title}}</h2> </div> <hr> <div class="link__short"> <p>{{link.desc}}</p> </div> </div> {% endfor %} But nothing is showing. I can see data in my admin panel. I did try to follow few tutorials but it still seems like something is wrong. My app is connected to project. -
My user password does not change, even though no errors occur when I use both password-reset views and password change views
I am pretty new in django. I am using an Abstract user, I have tried to change the password using both PasswordReset views, PasswordChangeViews and even on the admin account as well as with the command prompt. I do not get any errors, everytime everything seems to work well but when I try to login again I realize that the old password still remains the same. I don't know what else I can do I tried using the admin account, PasswordChangeViews, PasswordResetViews, and command line. I get no errors. Everything looks like it is working fine but when I login after changing the password, the password still does not change #User Model class User(AbstractUser): class Role(models.TextChoices): ADMIN="ADMIN",'Admin' STAFF="STAFF",'Staff' CUSTOMER="CUSTOMER",'Customer' CENTRAL="CENTRAL",'Central' MONITOR="MONITOR",'Monitor' username = models.CharField(max_length=200, null=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(null=True, unique=True) role=models.CharField(max_length=50, choices=Role.choices, null=True) updated = models.DateTimeField(auto_now =True) created =models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS= ['username','role'] class Meta: ordering =['-updated','-created'] def save(self, *args, **kwargs): if not self.pk: self.role= self.base_role return super().save(*args,**kwargs) #Views def passwordChange(request): user=User.objects.get(username=request.user.username) if request.method == 'POST': form = ChangePasswordForm(user=user,data=request.POST) if form.is_valid(): form.save() userp=User.objects.get(email=request.user) userp.set_password(form.clean_new_password2()) userp.is_active=True userp.save() update_session_auth_hash(request, userp) print(userp.check_password('XXXXXXXX')) #(XXXXx is actually hardedcoded password to chack if password changed at this point and i get True) … -
How to Login with a Custom User Model Table in Django 4.1.1?
I'm making an educational website in Django 4.1.1, and i need students to be able to register and login, so i created a Custom User Model Table in my models.py file. from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import UserManager class Custom(UserManager): def create_user(self, username, email=None, password=None, **extra_fields): return self._create_user(username, email, password, **extra_fields) class Student(AbstractUser): objects = Custom() sex = models.CharField(max_length=50,default='male') is_superuser = None is_staff = None groups = None user_permissions = None class Meta: verbose_name = "Student" verbose_name_plural = "Students" def __str__(self): return self.username and then i created an HTML registration form to get data from the user {% load static %} <html> <link rel="stylesheet" href="{% static 'css/register.css' %}"> <form method="post"> {% csrf_token %} <input type="text" name="firstName" placeholder="First Name" required minlength="3" maxlength="30"> <input type="text" name="lastName" placeholder="Last Name" required minlength="3" maxlength="30"> <input type="text" name="username" placeholder="Username" required minlength="3" maxlength="30"> <small>{{error}}</small> <input type="email" name="email" placeholder="Email" required maxlength="64"> <small>{{error}}</small> <input type="password" name="password" placeholder="Password" required minlength="8" maxlength="32"> <input type="password" name="passwordAgain" placeholder="Confirm Password" required minlength="8" maxlength="32"> <small>{{paswword_error}}</small> <input type="radio" name="sex" value="male" checked>Male</input> <input type="radio" name="sex" value="female">Female</input> <button type="submit">Submit</button> </form> <script src="{% static 'js/register.js' %}"></script> </html> and then i set up my views.py file to get the data and store it the database … -
Django channels add object at wrong model
I am making a chat app with django channels and it has 2 consumers. One is for the team chat and the other for personal. I am adding history for the chat. There are two models. "Chat" and "Chat2". Chat is for team and Chat2 for personal. The history is working with the team chat and the messages are added to the "Chat" model. But with personal it is added to "Chat" instead of "Chat2". Here are the models: class Chat(models.Model): team_id = models.ForeignKey(Team,on_delete=models.CASCADE,null=True) username = models.CharField(max_length=200,null=True) message = models.CharField(max_length=200,null=True) profile_pic = models.ImageField(upload_to='chat/',null=True) class Chat2(models.Model): username = models.CharField(max_length=200,null=True) username2 = models.CharField(max_length=200,null=True) message = models.CharField(max_length=200,null=True) profile_pic = models.ImageField(upload_to='chat/',null=True) room_name1 = models.CharField(max_length=200,null=True) And here are the two consumers(The consumers are in the same file but I add it separately for cleaner code): class ChatConsumer(AsyncWebsocketConsumer): @sync_to_async def get_profile(self): return self.scope['user'].profile async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['profile_name'] team = text_data_json['team'] profile = await self.get_profile() profile_pic = profile.profile_pic.url … -
How can I connect to a locally hosted site within a docker container?
I'm trying to connect to a docker container's locally hosted address. I'm using Django to serve a website within the container, and I want to connect to it on my local machine. How can I access this site from my local machine? I've tried to inspect the container and found that the local IP address is 172.28.0.4. Even after specifying the correct port on my browser, it still won't connect. The port 8000 is exposed in the container already, and added to the list of ports in the compose file. What can I do to fix this issue? -
when submitting the form, it is showing an error when recording. exiting test is_valid
if form.is_valid(): Errors field: * Cover This field is required. print ( request.POST ) <QueryDict: {'csrfmiddlewaretoken': ['yrPm4Vywus5cMjDNm34zQ8FVyJLdphAK95ErrIhEabOO19ss5ObAhOQe2eM6KO1t'], 'Codigo': ['5'], 'Titulo': ['Reforma do Estado e administração pública gerencia'], 'Capa': ['092022 - G DA SILVA REGO (DAS-SIMPLES) (1).pdf'], 'Sinopse': ['092022 - G DA SILVA REGO (DAS-SIMPLES) (1).pdf'], 'Codigo_grupo': ['3'], 'Codigo_autor': ['2'], 'Data_Publicacao': ['17/10/2022'], 'Edicao': ['7 edição']}> contexto = {'form': form } print ( contexto ) {'form': } models.py `class Livros(models.Model): Codigo = models.IntegerField(blank=False, null=False, primary_key=True) Titulo = models.CharField(max_length=50, blank=False, null=False) Capa = models.FileField(upload_to='capas/') Sinopse = models.FileField(upload_to='sinopse/') Codigo_grupo = models.ForeignKey(Grupos, on_delete=models.CASCADE, db_index=True, blank=False, null=False) Codigo_autor = models.ForeignKey(Autor , on_delete=models.CASCADE, db_index=True, blank=False, null=False) Data_Publicacao = models.DateField(auto_now = False , auto_now_add = False) Edicao = models.CharField(max_length=20, blank=False, null=False) def __str__(self): return str(self.Codigo)+' - '+self.Titulo **forms.py** `class LivrosForm(ModelForm): class Meta: model = Livros fields = ('Codigo','Titulo','Capa','Sinopse','Codigo_grupo','Codigo_autor','Data_Publicacao','Edicao',) ` **views.py** ` def livro_novo(request): form = LivrosForm(request.POST or None) if form.is_valid(): form.save() else: # Added else statment msg = 'Errors: %s' % form.errors.as_text() print ( msg ) print ( request.POST ) contexto = {'form': form } print ( contexto ) print (form.errors) return redirect('core_lista_livros') ` The form fields are filled in according to the class. what could be missing -
Use API call of payment gateway to change order status from "Pending" to "Completed"
I am using Django python and this is my first year in python programming I am writing a program where the client places an order. So in models.py I have an order object with field "Payment Status" with field choices: Pending and Completed. The default for this field is "Pending" but I want to change it to "Completed" once an API call shows the payment collection event is "COMPLETED." How can I capture payload data from API to change my order status from "pending" to "completed" once the transaction is successful? This is what I have in my views.py so far: @csrf_exempt def test_api(request): url = "https://2a45-217-21-116-220.in.ngrok.io/webhooks/intasend" payload = request.body headers = { 'Content-Type': 'text/plain' } response = requests.request("GET", url, headers=headers, data=payload) return JsonResponse(response.text, safe=False) -
Does Django have functionality to restore scroll position after browser BACK button was clicked?
I have a list that doesn't fit the screen vertically. User scrolls the list, then selects an item. Then user returns by pressing BACK browser button. Is there a way to return same scroll position? -
How to launch empty django projects quickly
I was looking for some advice. It takes me a long time to deploy a django project, I have to setup the server, install libraries, configure NGINX and get all the django internals working. I was looking into Docker or Puppet as quick was to create a cookie cutter for Django so I can deploy quickly but I've not used them much and am not entirely sure it's the best approach. If you needed to deploy an empty, running django app frequently, how would you do it? Thanks -
Why is my django_framework so prone to assertion errors
As the title I use "VScode" for programming and the environment is built on "anaconda" I actually simulate a code execution according to the teaching video, but the following errors related to the ".is_valid()" method will appear. The original situation is that the "save" method cannot be called, but when I restart "VScode", sometimes the error occurs Back to normal, in other words, there is no problem with the programming itself. Just encountered another error about the ".is_valid()" method, but this time with the "errors" method... I'm really confused. After all, the code is fine. Where is the problem, the "IDE" or the environment setup...? The "Put" method is super prone to situations! Learning Resources :https://www.bilibili.com/video/BV1rU4y1C7Vi?p=12&vd_source=68c365c9dd4a2dc36b283c24e59f47cd -
How to use suiteQL to query Image field?
I had one image field with the id 'custitem_test_img' on the Item record, Item internal id is '1234', I made one SuiteQL like the below: SELECT Item.custitem_test_img FROM Item WHERE Item.id = 1234 And I got one error back with a message: Error: Search error occurred: Field 'custitem_test_img' for record 'item' was not found. Reason: UNSUITABLE - Unsupported data type 'IMAGE' Any idea how to query the Image type field by SuiteQL? -
how to avoid extra spacing in template while using if endif condition in template django
i am retrieving information from the database and using {%if%} and {%endif%} condition so if that field is blank it does not cause any problem but when that field does not have any value it creates a new blank line in place of that looks bad in styling I saw an answer use this {%if -%} {%- endif %}it doesn't work and throws the error all I want if field is blank do not create any new blank line and render second line below that without creating any whitespace any suggestion will be helpfull -
Adding new item to foreign key field when creating an item for which it is related
I have two models apartment and image defined as class Apartment(models.Model): name = models.CharField(...) price = models.DecimalField(...) class Image(models.Model): apartment = models.ForeignKey(to="Apartment") I have them set up this way so I can have Many Images to One Apartment ManyToOne Rel Is there a way to add new Images when adding a new Apartment? There is no field for Images in the Apartment admin section -
Serving static files after deployment with django 2.2
I deployed my site at the level of my host, but the imgaes are not displayed. I did python manage.py collectstatic and it copied the files to my STATIC_ROOT myprojet/settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] STATIC_URL = 'static/' STATIC_ROOT='/home/www/mySite.com/static/' index.html {% extends 'layout/base.html' %} {% load staticfiles %} {% block content %} <img src="{% static 'images/icone.png' %}" style="width:350px;height:100"> {% endblock content %} I used {% load staticfiles %} as i am using django 2.2 but the images are not showing I don't know where the problem is. -
Integrity eror not null constraint failed
Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: Cart.cart_id #mymodel: class Cart(models.Model): cart_id=models.CharField(max_length=250,blank=True) def _cart_id(request): cart=request.session.session_key if not cart: cart=request.session.create() def add_cart(request,product_id): product=Product.objects.get(id=product_id) try: cart=Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart=Cart.objects.create(cart_id=_cart_id(request)) cart.save() -
how to authenticate user using the Custom user table with the phone as username in Django
I'm using a Custom user in my django application and it works fine when i create the user , but the problem happens when i try to authenticate the user as am using phone as username it simply not working. here is my code : class CustomUserManager(BaseUserManager): def create_user(self, phone, password=None): if not phone: raise ValueError('Users must have a phone number') user = self.model( phone=phone, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, password): user = self.create_user( phone, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.user_type = 'admin' user.save(using=self._db) return user class CustomUser(AbstractUser): """ Extends Django AbstractUSer as a custom user model """ user_type_choices = ( ('client', 'Client'), ('supplier', 'Supplier'), ('admin', 'Admin'), ) username = None phone = models.CharField(max_length=200, unique=True, verbose_name=_( "Phone"), help_text=_("Phone number of the user")) user_type = models.CharField(max_length=200, choices=user_type_choices, verbose_name=_( "Type"), help_text=_("Type of the user"), default='client') company_name = models.CharField(max_length=200, verbose_name=_( "Company Name"), help_text=_("Company name of the supplier"), blank=True, null=True) email = models.EmailField(max_length=200, verbose_name=_( "Email"), help_text=_("Email of the supplier"), blank=True, null=True) establishment_date = models.DateField(verbose_name=_("Establishment Date"), help_text=_( "Establishment date of the supplier's company"), blank=True, null=True) # number_of_projects = models.IntegerField(verbose_name=_("Number of projects"), help_text=_( # "Number of projects the supplier has"), blank=True, null=True) # tax_id = models.FileField(upload_to='media/tax_id', verbose_name=_( … -
How to fetch related entries in Django through reverse foreign key
Django newbie here! I am coming from .NET background I am frustrated as to how to do the following simple thing: My simplified models are as follows class Circle(BaseClass): name = models.CharField("Name", max_length=2048, blank=False, null=False) active = models.BooleanField(default=False) ... class CircleParticipant(BaseClass): circle = models.ForeignKey(Circle, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) status = models.CharField("Status", max_length=256, blank=False, null=False) ... class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="Email", unique=True, max_length=255, validators=[email_validator]) first_name = models.CharField(verbose_name="First name", max_length=30, default="first") last_name = models.CharField(verbose_name="Last name", max_length=30, default="last") ... My goal is to get a single circle with participants that include the users as well. With the extra requirement to do all that in a single DB trip. in SQL terms I want to accomplish this: SELECT circle.name, circle.active, circle_participant.status, user.email. user.first_name. user.last_name FROM circle JOIN circle_participant on circle.id = circle_participant.id JOIN user on user.id = circle_participant.id WHERE circle.id = 43 I've tried the following: Circle.objects.filter(id=43) \ .prefetch_related(Prefetch('circleparticipant_set', queryset=CircleParticipant.objects.prefetch_related('user'))) This is supposed to be working but when I check the query property on that statement it returns SELECT "circle"."id", "circle"."created", "circle"."updated", "circle"."name", "circle"."active", FROM "circle" WHERE "circle"."id" = 43 (additional fields omitted for brevity.) Am I missing something or is the query property incorrect? More importantly how … -
How to make the error messages not appear below the fields, but on top of the table Django
I'm writing a Django site, I made a registration form, but I don't like the fact that error messages appear under the corresponding fields, thereby stretching the table I want these messages to be displayed somewhere above the form, is this possible? -
Django listings: django displays FK's object instead of value
I am using django_listing in order to create a table: class SpotTableView(ToolbarListingView): template_name = f'{templates_dir}tables/spot.html' update_success_redirect_url = LISTING_REDIRECT_NO_EDIT save_to_database = True def get_listing_instance_update_listing(self): return Listing(Spot, editable=True, editing=False, edit_on_demand_options={'has_paginator': False}, edit_on_demand=True, gender__input_type='radio', save_to_database=True, selection_position='left', selection_multiple=True, selectable=True, selection_initial=[3, 4], per_page=5, has_toolbar=True, toolbar_placement='top', toolbar=Toolbar( InsertToolbarItem(), EditToolbarItem(), DeleteToolbarItem(), SortSelectToolbarItem(), PerPageSelectToolbarItem(choices='5,10,25,50,100,-1:All'), ) ) When the data table loads the FK's object name is displayed instead of the integer representing the FK's model's index. table I am declaring the FK inside the model as following: mid = models.ForeignKey('Metadata', default=1, verbose_name="mid", on_delete=models.SET_DEFAULT, db_column="mid") How can i make it display the value of the FK, instead of the model? -
How to check current URL/endpoint in django if statement
I have a button on a base template that just takes you back (history.back()) on every page except for one specific page. I assume there's a simple one line like {% if URL == specificURL %} but for the life of me I can't figure out how to do it. Im trying to do it within the html, but I'll happily take any other suggestions if something else would work Its a light site and I could take the button off the base template and just put separate logic on every html page but that's obviously bad for scale should also probably preface that I'm definitely beginner for Django -
Open jquery modal with django
how can I open the modal with Django? my jquery modal is in signup.html and my modal open button is in base.html. -
How to call a python function with annotations?
I have a function in another annotated method and there is a problem. I call it through django and get all sorts of errors. like this. views.py: ` def callbot(): bot_activate = bot.Command.callBot() return render(request, bot_activate) def output(request, temlate_name='custom_change_form.html',): callbot() print('work') return render(request, temlate_name) **bot.py** @logerrors def do_echo(update: Update, context: CallbackContext,): print('HELLOOOOO') chat_id = update.message.chat.id text = update.message.text p, _ = Profile.objects.get_or_create( external_id=chat_id, defaults={ 'name': update.message.from_user.username, } ) MessagePanel( profile=p, text=text, ).save() reply_text = f"Your ID: {chat_id} \n{text} \n " update.message.reply_text(text=reply_text,) @logerrors def send_text(update: Update, context: CallbackContext,): chat_id = update.message.chat_id text = update.message.text commandname = CommandsForButtons.objects.filter(is_active=True) print('Its worked') for mess in commandname: mess_send = mess.command_text update.message.reply_text(text=f'It\'s test message: {mess_send}') do_echo(update, context) @logerrors def send_hand_message(update: Update, context: CallbackContext,): chat_id = update.message.chat_id text = update.message.text hand_message = HandMadeMessage.objects.all() update.message.reply_text(text=f'It\'s test message: {hand_message}') class Command(BaseCommand): help = 'Telegram-Bot' def handle(self, *args, **options): hand_message = HandMadeMessage.objects.all() request = Request( connect_timeout=0.5, read_timeout=1.0, ) bot = Bot( request=request, token=settings.TOKEN, base_url=getattr(settings, 'PROXY_URL', None), ) to_bot_panel, _ = BotsPanel.objects.get_or_create( bot_id = bot.get_me().id, bot_name = bot.get_me().first_name, bot_nickname= bot.get_me().username, bot_token= bot.token ) print(bot.get_me()) updater = Updater( bot=bot, use_context=True, ) #Commands def callBot(): return send_text(Update, CallbackContext) updater.dispatcher.add_handler(CommandHandler('get', send_text,)) updater.dispatcher.add_handler(MessageHandler(Filters.text, do_echo)) updater.start_polling() updater.idle() ` Maybe u guys know what i should to …