Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to find or match two names which has different special characters django
I am trying to populate cities in a state using OpenstreetMaps API to my django application. The database was populated with some cities already. I am facing duplicate data issue since the name in cities sometime has special characters in it. For example in country Turkey, The state Bursa has city Gursu. My database has a city object with name Gürsu. And the city name from Openstreet Map API is Gürsü. I am trying to find a solution to match existing city with special character name and update it if it exists. So that I can avoid duplicates. -
unique_together does not replace primary key
In my Django app, I want to insert a record with a composite primary key. Apparently this should be possible by making use of "unique_together". I'm quite sure this code was working in the past, but for some reason it does not seem to be working now. This code used to run on a Linux VM, and now I'm hosting it in Google App Engine. However I don't see how this can be the cause for this error. class TermsAndConditionsDocument(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE, verbose_name=_("Organization")) language = models.CharField(_('Language'),choices=LANGUAGE_CHOICES, max_length=5, help_text=_("The language of the content.")) content = models.TextField() class Meta: unique_together = ('organization', 'language') The error: IntegrityError at /transactions/settings/terms_and_conditions null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, nl-BE, <p>B</p>, 10). According to what I've read, using "unique_together" should cause Django to not need or include an ID as primary key. I checked the database, and the ID field DOES exist. I do not understand where the database constraint and the ID field are still coming from? -
Docker Django uWSGI strange connection error
I'm trying to test a production environment of a Django app in a docker container, using a uWSGI server. My dockerfile looks like this: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY config/requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ EXPOSE 8000 CMD ["uwsgi", "--ini", "./uwsgi.ini"] and my uwsgi.ini like this: [uwsgi] http = :8000 chdir = ./ module = testproject.wsgi master = 1 processes = 2 threads = 2 When I build the container and run it, everything seems to work, but when I visit localhost:8000, rather than seeing my app, I get this error: [uwsgi-http] unable to connect() to node "127.0.0.1:61104" (3 retries): Connection refused I have no idea where this 61104 port is coming from (it's not specified anywhere), but I think the issue is that uWSGI can't properly connect to django... I've tried setting debug=False in the settings.py, and also adding that weird port to allowed hosts, but no dice. If anyone knows the answer to this I'd appreciate it! -
How to access buttons in a separate HTML file in the HTML file it is included in as header?
So I'm making an application which require a header. On this header are navigation buttons and whatnot. I need to access these buttons at the respective homescreen where this header html is included in. However, when i try to access these buttons they wont do anything, even though I've got an if-statement which calls for all of these buttons if pressed. I've tried separating the Header.html to see if it works as a normal page, which it does. It only doesn't work when it is included as a header. The HTML of the header: <form method="POST"> {% csrf_token %} <div class="sidenav"> <button type="submit" name="vergelijken" value="vergelijken">Vergelijken</button><br> <button type="submit" name="dag" value="dag">Dag</button><br> <button type="submit" name="week" value="week">Week</button><br> <button type="submit" name="maand" value="maand">Maand</button><br> <button type="submit" name="jaar" value="jaar">Jaar</button><br> &nbsp; <button type="submit" name="live" value="live">Live</button> {% load static %} <img src="{% static 'images/rdot.png' %}" class="rdot_logo"/> </div> </form> The django code: def header(request): global keuze if request.method == "POST": if request.POST.get('vergelijken'): print('hallo') return HttpResponseRedirect('/vergelijk/') elif request.POST.get('dag'): keuze = 'dag' elif request.POST.get('week'): keuze = 'week' elif request.POST.get('maand'): keuze = 'maand' elif request.POST.get('jaar'): keuze = 'jaar' elif request.POST.get('live'): keuze = 'live' return render(request, 'header.html') Apologies, variables are in dutch. So basically I need these if statements in the django code to work … -
In Django, does `queryset is None` evaluates the queryset?
Is Django queryset evaluated in below cases? If no, then why? 1. if queryset is None: pass 2. from django.db.models.query import QuerySet if isinstance(queryset, QuerySet): pass Is it because in both the cases python performs object reference comparison, which does not lead to a query? -
Dynamic JS and Django Calculator
I have no clue of JS, I copied this and modified it in a 4 hours so please be kind. I have a simple calculator. The concept behind is this. 1. There are check boxes which take their number/integer value from the database. Check boxes appear according to the number of entries in the database. 2. When a check box is clicked it's value is to show in the display of the calculator. 3. By checking two or more check-boxes, their values get added together and then displayed on the display. 4. By Un-checking a box the value is to be deducted from the display and the remaining value is to show. I'm able to add two values but when there are more elements the values don't add up. When I un-check a box and check it again the value adds up in the total again and gives the total of 3 values instead of 2. (the third being it self all over again) The value isn't deducting from the total. cal.html <head> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> </head> <body> <div class="calc"> <form name="form"> <input class="calc-display" > </form> <table> <br> {% for i in food_data %} <tr> <td><input type="checkbox" id="foodCheck" data-value="{{i.item_price}}" … -
Add custom ROW in Django admin view
I want to add a custom ROW in my django admin page, such that the last row contains some values specified by me. I tried searching but only found things like adding a new column (using list_display ) or adding entirely new features using changelist_view function (like a button to perform an action or adding a chart etc) . What I want to do is: add a ROW to the table(containing the objects of the model) which is generated by django's default admin view. -
I want to exceute one process only after completion of another process in my django application using celery
I am new to the celery thing. I want to run one process only after the completion of another one. While searching I found one code class CallbackTask(Task): def on_success(self, retval, task_id, args, kwargs): print("success") pass def on_failure(self, exc, task_id, args, kwargs, einfo): print("fail") pass @celery.task(base=CallbackTask) # this does the trick def add_val(x, y): time.sleep(20) return x + y while running that code, it shows status in the following order: Received task //After 20 min timer success(it is getting printed from 'on_success' method) 3.task completed (#ans-7) Actually, the problem here is 'success' is getting printed before my actual answer, if there is any way that I get that after my answer, then I can easily put my second process in the 'on_success' method and execute it. -
I want to make .bat file on the desktop that once clicked the file starts django python server, and opens Chrome
Make .bat file from django that runs the server once clicked and opens chrome browser. @ECHO ON start cmd.exe /C "python manage.py runserver && cd C:\Users\admin\Desktop\JUDICIARY\ && C:" start C:\"Program Files (x86)"\Google\Chrome\Application\chrome.exe "http://127.0.0.1:8000/" The .bat file opens the chrome browser but it shows 'This site can't be reached' but if I start the server manually then if I open the .bat file it opens without problems. -
Django_select2 : How to filter ModelSelect2Widget queryset with a request data? (Django_tables2 + Django_filter +Django_select2 )
I use django_tables2 with django_filter according to django_tables2 tutorial: #views.py from django_filters.views import FilterView from django_tables2.views import SingleTableMixin class FilteredCarListView(SingleTableMixin, FilterView): table_class = CarTable model = Car template_name = 'template.html' filterset_class = CarFilter def get_queryset(self): return self.model.objects.filter(owner_id=request.user.id) Also I want to use django_select2 in django_filter: I want to have a filter's field and its ModelSelect2Widget with the same filter as in FilteredCarListView.get_queryset(self). For filter's field I found this decision (I guess it is not DRY): # filters.py from .models import Car from django_select2.forms import ModelSelect2Widget def get_cars(request): return Car.objects.filter(owner_id=request.user.id) class CarFilter(django_filters.FilterSet): car = django_filters.ModelChoiceFilter( queryset = get_cars, field_name='car', widget = ModelSelect2Widget( model = Car, search_fields=['car__icontains']) But how to limit choises in ModelSelect2Widget to display current user's cars only? -
Custom MultipleChoiceField does not preserve model's values
I have this form, where I customized the way items are displayed using the choices attribute. This works fine and users names are correctly displayed, but the problem is on edition (i.e. where the Form is given an instance of Story with existing assignees), the corresponding <li> are not selected... models.py class Story(BaseModel): assignees = models.ManyToManyField(User, blank=True, related_name="assigned") forms.py class StoryForm(forms.ModelForm): assignees = MultipleChoiceField(choices=[(user.id, user.get_full_name() or user.username) for user in User.objects.all()]) view.py def story_edit(request, story_id): if request.method == 'POST': story = get_object_or_404(Story, id=story_id) form = StoryForm(request.POST, instance=story) if form.is_valid(): form.save() else: story = get_object_or_404(Story, id=story_id) form = StoryForm(instance=story) return render(request, 'story_form.html', {'form': form}) story_form.html <p> {{ form.assignees.errors }} {{ form.assignees }} </p> I tried adding the initial arg to the MultipleChoiceField (see below), but nothing changed. class StoryForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StoryForm, self).__init__(*args, **kwargs) self.fields['assignees'] = MultipleChoiceField(choices=[(user.id, user.get_full_name() or user.username) for user in User.objects.all()], initial=[user.id for user in self.instance.assignees]) -
Update datetimefiled of all related models when model is updated
I have two models (Post and Display). Both have Datetime-auto fields. My problem is that i want to update all display objects related to a post, once a post is updated. I have read here that you could override one models save method, but all the examples are About updating the model with the foreign key in it and then call the save method of the other model. In my case it's the other way arround. How can i do this ? class Post(models.Model): title = models.CharField(max_length=40) content = models.TextField(max_length=300) date_posted = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) rooms = models.ManyToManyField(Room, related_name='roomposts', through='Display') def __str__(self): return self.title def get_absolute_url(self): return "/post/{}/".format(self.pk) class Display(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) isdisplayed = models.BooleanField(default=0) date_posted = models.DateTimeField(auto_now=True) def __str__(self): return str(self.isdisplayed) i want to update the date_posted of all related Display-objects once their related post is changed. I do not know if overriding the save-method works here. -
how do link to function in view into html form
I am beginner about Django, I don't know get data from HTML form. How can I fix? Help me, please! <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Exmaple Form</title> </head> <body> <form method="post" action="{% %}"> {% csrf_token %} <p>First Name: <input type="text" name="firstname"></p> <p>Last Name: <input type="text" name="lastname"></p> <p><input type="submit" value="submit"></p> </form> <p>{{ first_name }}</p> <p>{{ last_name }}</p> </body> </html> Function get data HTML form def index(request): return render(request, 'form.html') context = {} first = request.POST.get['firstname'] last = request.POST.get['lastname'] context = { 'first_name': first, 'last_name': last } return render(request, 'form.html', context) -
django-tables2 max total results
I want to limit the max total results. I only want 1 page with max 20 results. How can I do that? Adding [:20] to the query gives an error Cannot update a query once a slice has been taken My SearchTestView Class: def get_context_data(self, **kwargs): context = super(SearchTestView, self).get_context_data(**kwargs) title_result = Title.objects.filter( Q(categories__steam_id=36) | Q(categories__steam_id=20) | Q(categories__steam_id=1) | Q(genres__steam_id=29) ).filter(release_date__lte=datetime.date.today()).distinct().order_by('- release_date') table = TitleTable(title_result) RequestConfig(self.request, paginate=False).configure(table) context['table'] = table return context -
How can I write Bulk Data(25 Lakhs) on an Excel Sheet using Python,Django,MYsql,Dataframe?
Actully I am new to Python.I am using Python with Django and MYsql. I have written a code to fetch bulk data(25 Lakhs) from MYsql database and split it into three variables and then write them on an Excel sheet which contains 3 sub sheets...Here is my view.py file.... all_dataobj=fetchdata.objects.all() pserializer=fetchdataSerializers(all_dataobj,many=True) res = [item for item in pserializer.data if 1 <= item.get('id') <= 1000000] res1 = [item for item in pserializer.data if 1 <= item.get('id') > 1000000 and item.get('id') <= 2000000 ] res2 = [item for item in pserializer.data if 1 <= item.get('id') > 2000000] df = pd.DataFrame([]) df1 = pd.DataFrame([]) df2 = pd.DataFrame([]) df = df.append(res) df1 = df1.append(res1) df2 = df2.append(res2) writer = ExcelWriter('fetchdata_sheet12.xlsx') df.to_excel(writer,'Sheet1',index=False) df1.to_excel(writer,'Sheet2',index=False) df2.to_excel(writer,'Sheet3',index=False) writer.save() But this code works totally fine with less data.As I am running it for 25 Lakhs data, the browser keeps on running and no excel sheet gets generated. I am stuck here for long time.Can anyone please help me out??????? -
I want to add tags like structure to my website
I have a field in my model where user enters it's skill. I want to show it like tags(as we do in stack overflow while posting questions) I tried searching for it but couldn't find it, may be because I am not quering the correct thing. -
django-tables2 How to set Verbose name for _set
I have a value ccu_set.all.first.player_count Which works perfectly, but I want to change the verbose name so that in the table it doesnt say "ccu_set.all.first.player_count". However when I do ccu_set.all.first.player_count = tables.Column(verbose_name= 'CCU', default='') It gives an error: ccu_set.all.first.player_count = tables.Column(verbose_name= 'CCU', default='') NameError: name 'ccu_set' is not defined -
Django - InheritanceManager is not working
I have the following simple models.py file: from django.db import models from model_utils.managers import InheritanceManager class Clique(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, blank=False) class Post(models.Model): created = models.DateTimeField(auto_now_add=True) headline = models.TextField() clique = models.ForeignKey(Clique, on_delete=models.CASCADE, blank=True, null=True) objects = InheritanceManager() def __str__(self): return self.headline class VideoPost(Post): video = models.BooleanField(default=True) class ImagePost(Post): image = models.BooleanField(default=True) So, there is a Clique model which can contain multiple Post instances. The Post instances can be ImagePost or VideoPost. Therefore, ImagePost and VideoPost both inherit Post. Now, let's say I want to retrieve the ImagePost subclass instances. So, I have the following view in my views.py file: class PostList(generics.ListAPIView): serializer_class = PostSerializer def get_queryset(self): return Post.objects.select_subclasses(ImagePost) When I pass the endpoint posts/ in the url, then this view will be triggered and it should give me only the ImagePost instances, right ? But I also get the VideoPost instances from the database: [ { "clique": "http://127.0.0.1:8000/cliques/1/", "comment_set": [], "created": "2019-06-18T09:52:47.929623Z", "headline": "FirstImagePost", "id": 1, "url": "http://127.0.0.1:8000/posts/1/" }, { "clique": "http://127.0.0.1:8000/cliques/1/", "comment_set": [], "created": "2019-06-18T09:53:20.266653Z", "headline": "FirstVideoPost", "id": 2, "url": "http://127.0.0.1:8000/posts/2/" } ] Why is this happening ? I walked through the official doc here . Can somebody help Just for the sake of completeness, … -
How can I loop a generator in this situation?
Here's the question. I want to use django's bulk_create to save more datas at once. But the original result I get from API is a generator with amount data in it. So I want to loop this generator and bulk save data. My trial was as below: # a generator with amount data l = ( item for item in range(1,100230, 1) ) # base model table class ModelDemo(models.Model): ... # main logic code limit = 2000 while l: bulk_list = [] for index, item in enumerate(l): bulk_list.append( ModelDemo( ... ) ) if index == limit: ModelDemo.objects.bulk_create(bulk_list) break It's obviously I would lose last 230 data, but I couldn't find the solution by now. Any commentary is very welcome. great thanks. -
Creating a clickable view for my template
I am trying to create a view template for my project. My app has 5 fields which include site_id(char),annotation(int),person_class(int),vehicle_class(int) and time(char). All entries in the table belong to one of the site_id (site_1, site_2 ....site_5). I want to create a view which displays the 5 site_ids on the webpage and clicking on them should open up a table of its corresponding data. I am new to django and currently facing problems understanding this implementation. Could someone point me to what I need to do? -
Allow API requests with X-CSRF headers from Laravel to Django Backend
I have Laravel framework with VueJS serving as the frontend. This frontend is hosted on xampp's localserver on ports 80,443 with the configured url "http://test.net". I send API requests from VueJS app using axios to a Django backend, where I have installed a working Rest framework (Accessible through Postman). The backend server is http://127.0.0.1:8000. Because the servers are different, I have installed django-cors-headers package and configured the settings.py file to include this package, and also include the middleware, as shown in the documentation. This is the axios request from Vue: let url = "http://localhost:8000/leadmanager/api/lead/"; axios.get(url) .then(res => console.log(res.data)) .catch(error => console.log(error)); Initially I got this error: Access to XMLHttpRequest at 'http://localhost:8000/leadmanager/api/lead/' from origin 'http://localhost:80' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. So I checked the documentation and installed django-cors-headers and included the Laravel website's url inside CORS_ORIGIN_WHITELIST. CORS_ORIGIN_WHITELIST = [ "http://test.net" ] After doing this, I get a different error. I suspected this would be because Laravel by default attaches x-csrf-token headers to the packets being sent out. Access to XMLHttpRequest at 'http://localhost:8000/leadmanager/api/lead/' from origin 'http://hawiya.net' has been blocked by CORS policy: Request … -
Django with Pandas accessing ForeignKey
I do not know Pandas so this may be trivial. I have this line of code: admin_data = pd.DataFrame.from_records(administrations.values()).rename(columns = {'id':'administration_id', 'study_id': 'study_name', 'url_hash': 'link'}) which is getting data from the administration model (administrations is a recordset) and using it. Rather than using study_id I would like to get the study name. With Djano ORM I would use study__name but I cannot do that here. How can I get the study.name instead of study.id into admin_data? models class administration(models.Model): study = models.ForeignKey("study") # Study name ... class study(models.Model): name = models.CharField(max_length = 51) # Study name ... -
Can not login with 'requests'
I'm trying to login and get a response. But i can not do it because of password encryption algorithm of django Is it possible in other ways? payload = {'username': self.request.user.username, 'password': self.request.user.password} response = requests.post('http://localhost:8000/api/login/',data=payload) Error: No active account found with the given credentials -
I can not get alll the data from the database with one query
I have to two tables in the postgresql database. In first one I have all descriptions of a vulnerabilities and in the second one I have all the product that are affected. Tables are conected via primary key. My problem is that I do not know how to get one description with all vulnerabilities in one query. I have tried with django-orm and raw postgresql queries without success. Here are my models: class Description(models.Model): description = models.TextField() file =models.CharField(max_length=50) date = models.DateTimeField(default=timezone.now) severity = models.CharField(max_length=10) exp_score = models.DecimalField(null=True, max_digits=5, decimal_places=1) impact_score = models.DecimalField(null=True, max_digits=5, decimal_places=1) cvss_score = models.DecimalField(null=True, max_digits=5, decimal_places=1) published_date = models.IntegerField() last_modified = models.IntegerField() cve = models.CharField(max_length=30) cve_url = models.CharField(max_length=1000) def __str__(self): return self.file class Meta: verbose_name_plural = 'Ranljivosti' class AffectedProductVersion(models.Model): data = models.ForeignKey(Description, on_delete=models.CASCADE) vendor_name = models.CharField(max_length=100) product_name = models.CharField(max_length=100) version = models.CharField(max_length=150) class Meta: indexes = [ models.Index(fields=['vendor_name', 'product_name', 'version']), ] def __str__(self): return self.vendor_name + '-' + self.product_name Is it possible to achieve this in one queryset? Query can be written in django-orm or raw postgresql. I will appreciate any suggestion to solve my problem. -
Setting Academic or Financial Years in Django
This may seem rather insignificant, but how do you set a financial or academic year, say 2018/19 or 2017/2018 in a Django model and reference the current financial year for querying, in this case 2019/20