Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redirect problems
I'm new in Django and I'm having problems with redirect the user after authorization. Here is 200 code in the console. def user_login(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}.") return redirect("test") else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form": form}) [27/Jan/2022 14:41:26] "POST /account/login/ HTTP/1.1" 302 0 [27/Jan/2022 14:41:26] "GET /account/test/ HTTP/1.1" 200 136 the same with redirect(reverse("test")) -
Django REST Framework Serializer Initialize variable in init
I am trying to initialize a django model's object inside a Serializer class. Lets say I have 2 models ABCD and WXYZ. I performed a filter on ABCD and send the results to a serializer. The serializer need to get an instance of WXYZ model using a field of ABCD model, and fetch some result. I want to get the WXYZ instance in the init method, so that I can access that across all functions in the serializer class. Models: class ABCD(): col1 = models.Integerfield(...) ... class WXYZ(): col2 = models.Integerfield(...) title = models.Charfield(...) ... views.py: # performed a filter on ABCD model abcd_objects = ABCD.objects.filter(...) results = ABCDserializer(abcd_objects, many=True).data serialzers.py class ABCDserializer(serializers.ModelSerializer): title = serializers.SerializerMethodField('fetch_title') ... def __init__(self, obj): ans = WXYX.objects.get(col2=obj.col1) self.wxyz_obj = ans def fetch_title(self, obj): return self.wxyz_obj.title class Meta: model = ABCD fields = ['title', ...] -
How to generate an id for a newly created model instance using django and DRF?
I am trying to figure out how to create instances of a model in my view. I have written a method in a class outside the view, that I am using to generate a random id for the model instance to be created: def generate_random_id(self, MyModel): """ Picks a random id for an object to be created in POST""" random_object = None if random_object is None: random_object = random.randrange(1, MyModel.objects.all().count() + 1) while MyModel.objects.all().filter(id=random_object).exists(): random_object = random.randrange(1, MyModel.objects.all().count() + 1) return random_object This method has worked for other model instances. I think the problem is in the view itself. views.py ... tag = Tag.objects.create( id=controller.generate_random_id(Tag), name='randomlycreatedtagfor test', language='de') ... I keep getting this error: duplicate key value violates unique constraint "app_tagging_pkey" DETAIL: Key (id)=(57949) already exists. However, here is my code for the model and the serializer. Maybe this is where I am doing something wrong. models.py class Tag(models.Model): name = models.CharField(max_length=256) language = models.CharField(max_length=256) objects = models.Manager() def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() return super().save(*args, **kwargs) def create(self, validated_data): tag_data = validated_data.pop('tag') Tag.objects.create(**tag_data) return tag_data def __str__(self): return self.name or '' serializers.py class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('id', 'name', 'language') def … -
Fetch API does not render views from django
This might be a beginner question, I'm new to Django. So I'm trying to create a login button where it would return an HttpResponse and I'm trying to get the strings from the response. I tried printing the result from fetch and it did seem to response with code 200 but for some reason I'm not able to get the content from the HttpResponse. Here's my javascript used to fetch the /login/ url: login-script.js function normalLogin(){ fetch("/login/", { method: "POST", headers: { "X-CSRFToken": getCookie("csrftoken"), 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json' }, redirect: 'follow', }).then(res => { console.log("Request complete! response:", res); // location.reload(); }); Here is also the code used to redirect users to the dashboard. views.py def login(request): if request.method == "POST": return HttpResponse("Here's a text") I'm trying to get the string from the HttpResponse but to no avail, it returns undefined. I tried res.body and res.header. I also looked at this but it does not work for me. Is there something I did wrong or mistake I make without realizing? Thanks Fetch API post data not receiving in Django view Getting HttpResponse in Django from Javascript fetch -
Django model fields not dynamic
I have this in my models. class School(models.Model): subscribed = models.BooleanField(default=True) invoice_date = models.DateField() remaining_days = models.IntegerField(default=30) def save(self,*args,**kwargs): self.remaining_days = (self.invoice_date - date.today()).days if self.invoice_date <= date.today(): self.subscribed=False else: self.subscribed=True return super().save(*args,**kwargs) The problem is the remaining days do not change dynamically. I thought it would when I was coding this. How can I make it change each new day??? -
Django - category and slug in url
I have a function that addds article to favourites when user hits the button. Everything was fine until I decided to add category to url address. Below you can see the code that I am trying to debug. models.py class Article(models.Model): author = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) title = models.CharField(max_length=254) category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True, related_name='articles') favourite = models.ManyToManyField(User, default=None, blank=True, related_name='favourite_article') slug = models.SlugField(unique=True, blank=True, max_length=254) def get_absolute_url(self): return reverse("article", kwargs={"category": self.category, "slug": self.slug}) views.py @login_required def FavouriteArticle(request, slug): article = get_object_or_404(Article, slug=slug) favourized = False if article.favourite.filter(id=request.user.id).exists(): article.favourite.remove(request.user) favourized = False else: article.favourite.add(request.user) favourized = True messages.success(request, 'Article is now available in favourites.') return HttpResponseRedirect(reverse('article', args=[str(category), str(slug)])) url.py urlpatterns = [ path('favourite_article/<category>/<slug:slug>', views.FavouriteArticle, name='favourite_article'), ] Could you please let me know what am I doing wong? -
Why is searching in <200 categories slower than searching in >6000 products?
Using line_profiler library to analyse my Django Ecommerce project, I find that searching in less than 200 Product Categories is slower than searching in over 6000 Products. As you can see in the image below, using a .get() method on the ProductCategory objects takes more than double the time of using .filter() on the Products, even though the Product.filter has to look through a list of values (categories__in). Does anyone have an idea as to why this is? :-)) -
I want to send SMS to the registered user regarding weather from fast2sms api
I want to sent SMS to all the registered users that have been saved in the extendeduser table.This table contains users phone number , so weather inforamtion is been getting from openweatherapi and if any city has weather conditions as overcastclouds then all the users will be sent SMS using fast2sms api as you can see the code def printit(): threading.Timer(10, printit).start() for i in user_data: city = i['town'] src = 'http://api.openweathermap.org/data/2.5/weather?appid=APP_ID=' url = src + city list_of_data = requests.get(url).json() temp = list_of_data['main']['temp'] newtmp = round(temp - 273.15, 3) condition = list_of_data['weather'][0]['description'] humidity = list_of_data['main']['humidity'] data = { "city": city, "temp": newtmp, "humidity": humidity, "condition": condition, "icon": str(list_of_data['weather'][0]['icon']), } print(data) if data['condition']=="overcast clouds": euser = extendeduser.objects.values('phone', 'user') q=[] for j in euser: q.append(j['phone']) url = "https://www.fast2sms.com/dev/bulk" querystring = {"authorization": "API_KEY", "sender_id": "ANNADATA", "message": "Overcast Clouds Seen", "language": "english", "route": "p", "numbers":q} headers = { 'cache-control': "no-cache" } response = requests.request("GET", url, headers=headers, params=querystring) print(response.text) print('\n'+city,' user '+str(i['user'])+' overcast condition',end='\n') printit() -
Django display every model owned by user
I have a HTML template file and in this file is the ticket itself (Ticket Model) and need I to display messages that belong to each ticket (TicketMessages Model). How can I do the following: -display me all TicketMessages (messages) that belong to this specific ticket. I need to get the current Ticket then display every user_message of this ticket? Models File class Ticket(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) description = models.TextField() ...... def __str__(self): return str(self.id) class TicketMessages(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) ticket = models.ForeignKey( Ticket, default=None, null=True, on_delete=models.CASCADE, ) admin_message = models.CharField(max_length=200, blank=True) user_message = models.CharField(max_length=200, blank=True) The Views File already gives me the ID of the current ticket def ticket_system_view(request, id): obj = Ticket.objects.get(id=id) if request.method == 'POST': user_form = TicketMessagesForm( request.POST, instance=TicketMessages(ticket=obj, user=request.user)) if user_form.is_valid(): form_save = user_form.save(commit=False) form_save.ticket = obj form_save.save() else: user_form = TicketMessagesForm() return render(request, 'ticket-system.html', {'obj': obj, 'user_form': user_form, }) My attempt looks like this in the template {% for i in request.user.ticketmessages_set.all %} <div> {% if ... %} {{ i.user_message }} {% endif %} </div> <br /> {% endfor %} The loop displayed nothing and secondly I would get all the … -
How to get time from user for work a function in Django
I write a app and this get price (priceapp) and news (newsapp) form several site. I want get a time like "daily 12:00" or "after 6 h" from user and send this price and news to telegram or other app selected from user. How I set time for get information and how to send result to users. -
how get only fields in django serializers
i used django.core.serializers to get data from model as below code from django.core import serializers ... serializers.serialize('json',production_time.production_items.all()) and i get response as below: [{"model": "BorseBots.exchangemonthlyproductionitem", "pk": 1308, "fields": {'name':'jack',...}} , ...] but i do not need 'model' and 'pk' fields so expect below: [{'name':'jack',...} , ...] or [{"fields": {'name':'jack' , ...}} , ...] how get this? need use loop to extract data in new list? using django2.2.* python3.8 -
Creating a notification for all project managers when there is a new data inserted into the inventory?
I need to automatically send a notification for every project managers after inserting a new data into the inventory, to notify them that there's a new item in the warehouse. Im new to django programming and i'm not familiar with using signals. Models.py class Item(models.Model): ItemName = models.CharField(max_length=255, blank=True, null=True) Quantity = models.IntegerField(null=True, default=1, validators=[ MaxValueValidator(100), MinValueValidator(0) ]) ModelNum = models.CharField(max_length=255, blank=True, null=True) Category = models.ForeignKey(Category,on_delete=models.CASCADE, null=True) date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) is_draft = models.BooleanField(default=True) reorder_level = models.IntegerField(blank=True, default=10, validators=[ MaxValueValidator(100), MinValueValidator(1) ]) class Meta: verbose_name_plural = 'Item' def __str__(self): return f'{self.ItemName}' class Notifications(models.Model): id=models.AutoField(primary_key=True) sent_to = models.ManyToManyField(CustomUser) message = models.TextField(null=True) message_reply = models.TextField(null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) Views.py def inventory(request): items = Item.objects.all() if request.method == 'POST': form = ItemForm(request.POST) if form.is_valid(): form.save() ItemName = form.cleaned_data.get('ItemName') messages.success(request, f'{ItemName} has been successfully added.') return redirect('inventory') else: form = ItemForm() context = { 'items' : items, 'form' : form, } template_name ='inventory-admin/inventory.html' return render(request, template_name, context) -
How do generate documentation with pydoc for django api?
I need to create documentation for Django API with pydoc Please help me -
xhtml2pdf dynamic frame height
I have some table template, that created with xhtml2pdf. I would like to add user information above table on each printed page. Here is html code: <div id="table_header"> <div>{{ data.user }}</div> <div>{{ data.title }}</div> </div> <table id="table" > </table> Here is style: @page{ size: a4 portrait; margin: 1cm; @frame content { -pdf-frame-content: table_header; top:1cm; left:1cm; height: 60pt; } @frame content { -pdf-frame-content: table; top:60pt; left:1cm; } /*rest of styles*/ } In fact, I'm not sure that user info will always be less than 60pt height (frame height). Is it possible to make frame height dynamic to prevent content overflowing? Seems, it's not possible to use height: auto; and height: 100%; here. Thanks. -
Uploading Scan Results in DefectDojo results in internal server error
i've tried many different things and hope to get some help here. While uploading some scan results in DefectDojo (running inside Docker containers) the application answers with "Internal Server Error", meaning it is not possible to upload files. Below, i have added the response in my Debian terminal. nginx_1 | 2022/01/27 09:09:15 [warn] 6#6: *36 a client request body is buffered to a temporary file /var/cache/nginx/client_temp/0000000002, client: xx.xx.xx.xx.xx, server: , request: "POST /product/1/import_scan_results HTTP/1.1", host: "xxx.amazonaws.com:8080", referrer: "http://xxx.amazonaws.com:8080/product/1/import_scan_results" uwsgi_1 | [27/Jan/2022 09:09:15] ERROR [django.request:224] Internal Server Error: /product/1/import_scan_results uwsgi_1 | Traceback (most recent call last): uwsgi_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute uwsgi_1 | return self.cursor.execute(sql, params) uwsgi_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 73, in execute uwsgi_1 | return self.cursor.execute(query, args) uwsgi_1 | File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 206, in execute uwsgi_1 | res = self._query(query) uwsgi_1 | File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 319, in _query uwsgi_1 | db.query(q) uwsgi_1 | File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query uwsgi_1 | _mysql.connection.query(self, query) uwsgi_1 | MySQLdb._exceptions.IntegrityError: (1062, "Duplicate entry '17' for key 'PRIMARY'") uwsgi_1 | uwsgi_1 | The above exception was the direct cause of the following exception: uwsgi_1 | uwsgi_1 | Traceback (most recent call last): uwsgi_1 | File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner uwsgi_1 … -
django dependent dropdown, How can I implement using ModelForm
I have already tried this method dependent. But not working for , Help me. models: class Country(models.Model): id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=50) class Meta: db_table = "countries" verbose_name_plural = 'countries' def __str__(self): return self.name somehow I can chain the country and state fields using ajax but can't store it to the data base. the form is showing errors. class State(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=50) class Meta: db_table = "states" def __str__(self): return self.name forms: class UserAddressForm(forms.ModelForm): class Meta: model = Address fields = ['full_name', 'phone', 'address_line1', 'address_line2', 'country', 'state', 'town_city', 'postcode'] -
django 3.2 and postgres 9 column must appear in the group by clause or be used in an aggregate function
in the admin.py i have a function that determinate a value for a field that doesn't exist in the database when i work with sqlite all it's fine but when i switch in postgres return an error "column must appear in the group by clause or be used in an aggregate function" admin.py ''' imp_f1 = OrdineDB.objects.filter( ~Q(ordine = None), ~Q(ordine__evaso = True), distinta__articolodb__articolo__articolo_lavo__id = id_fase1) .aggregate(total = Sum( quantita_fase1 * F('distinta__articolodb__quantita')) * F('quantita'))['total'] or 0 print(f'impegno f1-{imp_f1}') ''' -
I want to extract a specific value from a string in python
I have a string from which I want to extract value for test1. The string is : I_ID [I_ITEM = [I_ITEM [test1 = F135], I_ITEM [test1 = W1972544]]]]] Any pointers will be helpfull -
Route53 , aws , dns [closed]
I have created a website using Django + gunicorn + Nginx. When i use AWSRoute 53 and I create a CNAME from my host name to a DNS instance name the system doesn't point to the site but to the NGINX start page. It's very strange With the normal Linux 2 AMI and a normal HTML page it works correctly . Is there anyone that can have any idea ? Thanks a lot -
How to count items when their quantity is below reorder level in django
Im confused in counting the items that are quantities are below reorder level. The reorder level is a column in the model of an item too, i think i need to compare their values in __lte in filters but it's not working. Models.py class Item(models.Model): ItemName = models.CharField(max_length=255, blank=True, null=True) Quantity = models.IntegerField(null=True, default=1, validators=[ MaxValueValidator(100), MinValueValidator(0) ]) ModelNum = models.CharField(max_length=255, blank=True, null=True) Category = models.ForeignKey(Category,on_delete=models.CASCADE, null=True) date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) is_draft = models.BooleanField(default=True) reorder_level = models.IntegerField(blank=True, default=10, validators=[ MaxValueValidator(100), MinValueValidator(1) ]) class Meta: verbose_name_plural = 'Item' def __str__(self): return f'{self.ItemName}' Views.py def dashboard_inventory(request): items_count = Item.objects.all().count() reorder_count = Item.objects.filter(Quantity_lte=reorder_level).count() context={ 'items_count' : items_count, } template_name ='inventory-admin/inventory-dashboard.html' return render(request, template_name, context) -
How do I remove <p> tag from django richtextfield?
I am getting p tag displayed after I post an image or question with ckeditor editor in django ..How can I remove the tag and get the image or text be displayed correctly. [https://i.stack.imgur.com/leLA4.png][1] -
How to check Gmail ID exists or not By Phone Number one bye one Automatically and save phone number which have Gmail ID exists
I want to make an automatic Phone nUmber checking software using phyton that will run in command prompt. Here is the video: https://www.youtube.com/watch?v=ynpmra8bry8 https://www.youtube.com/watch?v=6pSMs7vSyvw I want to make a automatic software like this video.. Please help me with Code If anyone know please share code with me.. thanks a lot -
How to deploy django app on Oracle Linux Server 7.9?
how can I deploy a django application to Oracle Linux Server 7.9 using Putty. Tried to follow this guide but it didn't work. -
maria data base connection error pandas.io.sql.DatabaseError: Execution failed on sql
I am trying to make some changes in the database for that I wrote a script but I think there is a problem with my db_connection I am sharing the script which wrote for the changes from django.conf import settings from farm_management.scripts.db_execute_query import get_data, mysql_db_connect, insert_data def get_boundary_coord(): """ This function will get values from boundary_coord and then return the values into lng and lat """ # create mysql database connection db_conn = mysql_db_connect() print(db_conn, "hello") get_lat_lng_query = "SELECT JSON_EXTRACT(boundary_coord, '$[0][0]') as lng, " \ "JSON_EXTRACT(boundary_coord, '$[0][1]') as lat" \ " FROM farm_management_farm WHERE boundary_coord IS NOT NULL and lng IS NULL and lat IS NULL" # call get_data function to execute get_lng_query, get_lat_query lat_lng_data = get_data(get_lat_lng_query) insert_lat_lng_query = "INSERT INTO `{}`.farm_management_farm(lng, lat) VALUES(%s, %s)".format(settings.IGROW_DB_NAME) # call insert data function by passing database connection, query, farm dataframe to execute insert query insert_data(db_conn, insert_lat_lng_query, lat_lng_data, "farm_management_farm") # close the database connection db_conn.close() def run(): get_boundary_coord() and mysql_db_connection function looks likes def mysql_db_connect(): """ This function creates a connection to mysql database """ db_config = settings.MYSQL_DB_CONFIG mydb = MySQLdb.connect(host=db_config['HOST'], user=db_config['USER'], passwd=db_config['PASSWORD'], db=db_config['NAME']) return mydb but when I am trying my script to make changes in the database It shows an error Exception … -
multiple collapse items that call one django view function, each should submit a different value
I have multiple collapse items. all items should call the same django function while submitting a different value each. I want to achieve this without using django forms dropdown menu. what changes should I make to the current HTML code: HTML: <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Filter Options:</h6> <a class="collapse-item" value='1' href={% url 'show_dashboard' %}>Option1</a> <a class="collapse-item" value='2' href={% url 'show_dashboard' %}>Option2</a> <a class="collapse-item" value='3' href={% url 'show_dashboard' %}>Option3</a> <a class="collapse-item" value='4' href={% url 'show_dashboard' %}>Option4</a> <a class="collapse-item" value='5' href={% url 'show_dashboard' %}>Option5</a> <a class="collapse-item" value='6' href={% url 'show_dashboard' %}>Option6</a> <a class="collapse-item" value='7' href={% url 'show_dashboard' %}>Option7</a> </div> </div>