Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run Django API that has 1 hour to execution time
I have an API that takes one hour to complete...I am trying to implement celery and run 2 times a day..So what is the best way to run an API asynchronously? -
AttributeError: module 'graypy' has no attribute 'GELFRabbitHandler'
I add LOGGING to my Django project settings: LOGGING = { 'handlers': { 'graylog_rabbit': { 'level': 'INFO', 'class': 'graypy.GELFRabbitHandler', 'url': os.getenv('LOG_RABBITMQ_URL'), 'exchange': os.getenv('LOG_RABBITMQ_EXCHANGE'), }, 'loggers': { 'django': { 'handlers': ['graylog_rabbit'], 'level': 'DEBUG', 'propagate': False, }, } and I install these packages in my venv: amqp==5.0.9 amqplib==1.0.2 graypy==2.1.0 graypy[amqp] but this error accured: ModuleNotFoundError: No module named 'graypy.GELFRabbitHandler' I use Pycharm in Windows. -
Please tell me how to put Excel data in several model columns
Hello~ I'm studying using django, and I'm trying to get help because I'm stuck, and I'm practicing uploading Excel files as storage materials, and I can see many examples of Excel data on Google, but the problem is that I don't know how to do various models. Current models include question models and elective models that refer to question and voter models as ForeignKey. In addition, the data of all models are currently empty, and the data value of Excel becomes the first value. I know it's hard to understand. The default_key (identifier) of the question is Question_text. The default_key (identifier) of Choice is Choice_text. The primary key of the voter is the voter_name. Therefore, Question_text and Potters_nm currently in Excel are identifiers and duplicate data. I've been asking this question for days and reading the official documents of Jango Excel and Jango export several times, but it's not working well at all. If you have a similar experience, please answer me. class Question(models.Model): question_text = models.CharField(primary_key=True,max_length=200) pub_date = models.DateTimeField('date published') slug = models.CharField(max_length=10, unique=True, default="question") def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) voters_name = models.ForeignKey('Voters', on_delete=models.DO_NOTHING) choice_text = models.CharField(primary_key=True, max_length=200) votes = models.IntegerField(default=0) def __str__(self): return … -
How to resolve BATON_REVISION' error in Django-baton
I try Django-baton official documentations to customize the appearnce of django baton but this error occur enter image description here -
how can i change is_active in database using a toggle button in python language
how can i change is_active in database using a toggle button in python language. index.html <table> {% if user_detail.user.is_active %} <td><label class="switch "> <input type="checkbox" id="{{user_detail.user_id}}" value="{{user_detail.user.is_active}}" checked> <span class="slider round"> </label> </td> {% else %} <td><label class="switch"> <input type="checkbox" id="status1" value="{{user_detail.user.is_active}}"> <span class="slider round"> </span> </label> </td> {% endif %} </table> -
phpserialize : a bytes-like object is required, not 'str'
I am converting a website from Cakephp to django and I am having problem using a function unserialize from php. $details = unserialize(temp); I converted this into python as -> from phpserialize import * details = loads(temp) I am getting this error a bytes-like object is required, not 'str' My data look like this -> a:15:{ s:9:"CandidateA";a:9:{ s:4:"mail";s:21:"somemail@gmail.com"; s:4:"name";s:22:"name1"; s:7:"something1";s:19:"something"; s:6:"mobile";s:13:"12345678"; s:7:"zipcode";s:8:"123456"; s:9:"address_1";s:18:"address1"; s:9:"address_2";s:5:"0987659"; s:15:"something2";s:9:"something3"; s:6:"street";s:24:"address2"; } s:6:"CandidateB";a:9:{ s:4:"mail";s:21:"somemail@gmail.com"; s:4:"name";s:22:"name1"; s:7:"something1";s:19:"something"; s:6:"mobile";s:13:"12345678"; s:7:"zipcode";s:8:"123456"; s:9:"address_1";s:18:"address1"; s:9:"address_2";s:5:"0987659"; s:15:"something2";s:9:"something3"; s:6:"street";s:24:"address2"; } ---- ---- ---- ---- ---- } ---- means that there are more repetition. Please help. -
Output the Json Response dictionary to the django template
I'm just starting to learn django. Please tell me how I can better implement my idea. JsonResponse sends a response to a separate url (url_to_django/load_table/), how do I output this dictionary to group.html? Html <tbody id="table_person_id"> {% if pers %} {% for pers in persons_list %} <tr> <th scope="row"><div><input class="form-check-input" type="checkbox" id="checkboxNoLabel1" value="" aria-label="..."></div></th> <th scope="row">{{forloop.counter}}</th> <th scope="col">{{persons_list.Id_Group}}</th> <th scope="col">{{persons_list.get_Type_Participation_display}}</th> <th scope="col">{{persons_list.display_id_people}}</th> <th scope="col">{{persons_list.Competencies}}</th> <td> <button value="{{person.Id_Group}}" onclick="delete_person(this.value)">delete</button> </td> </tr> {% endfor %} {% endif %} </tbody> <script> function loadTable() { let xhttpTableGrops = new XMLHttpRequest() xhttpTableGrops.onreadystatechange = function (data) { if (this.readyState === 4 && this.status === 200) { document.getElementById("table_person_id").innerHTML = this.response } } xhttpTableGrops.open("GET", "/main/url_to_django/load_table/", true) xhttpTableGrops.send() } </script> Urls.py urlpatterns = [ path('', views.start, name="start"), path('group', views.Groups.as_view(), name='group'), path( 'url_to_django/load_table/', views.load_table, name='load_table') Views.py def load_table(request): if request.method == "GET": if request.user: try: persons = AkpGroup.objects.filter(Id_Incidents=120) # запрос в базу данных except AkpGroup.objects.DoesNotExist: persons = None pers = persons.all().values() persons_list = list(pers) return JsonResponse(persons_list, safe=False) else: return HttpResponse(status=403) else: return HttpResponse(status=405) -
How avoid duplicate records when use annotate() in queryset
I get this queryset for some method an receive one record candidates_qs = self.filter_job_type_language_zones(job_type_id, filter_languages, filter_zones) Then i need to cast a charfield to integerfield to compare against some value candidates_qs = self.filter_job_type_language_zones(job_type_id, filter_languages, filter_zones) candidates_qs = candidates_qs.annotate( # cast answer_text as integer to compare with question value as_integer=Cast('candidatejobtype__questions_answers__answer_text', IntegerField())) After that my queryset have duplicated records. I try distinct() but didn't work. How avoid duplicate records? -
Korean version of Reddit: Failed to load resource: the server responded with a status of 403
I had so much fun with MSOutlookit (a website basically rekinning Reddit into an Outlook interface). So I’m building a Korean version of it, using their codes (https://github.com/attaxia/MSOutlookit). Im basically scrapping posts from a website called DCInside (a Reddit-like website popular in Korea) Here is the problem. An image scrapped from a post in this website is only shown on my website when Chrome Developer Mode is enabled. When the mode isn’t turned on, I get 403 error. At first, i thought it was a size problem of img on css. But doesnt seem to solve the issue. Here is the code i used <div class="crawl_contents"> {{ data.content|safe }} </div> Please help me guys! -
How to display tableau dashboard in Django?
I want to embedded Tableau dashboard result into one of the html pages in Django. Can it be done? Thank you for any advice! -
Add new value and old value columns in Django simple history
I need to implement a History model and track some events like: New project, Edit project, etc I found this app that does almost exactly what I want. I've been following the documentation but I have a problem. The tables created contain the following columns: history_user, history_date, history_change_reason, history_id, history_type Which is great, but I would also like to have some info about what fields changed in case there is an Update type event. How could I add a New value and Old value columns to the rows generated by the app? I've found this about History Diffing but it's not clear to me how to hook it up. All my models look like this right now: class ModelName(models.Model): #model fields history = HistoricalRecords() -
how to make breakpoint pycharm pyx file?
I have installed cython, whenever tried for a breakpoint using python (.pyx) file PyCharm IDE, I could not create breakpoint (.pyx) file, -
Not able to view static files on template
This project is working but unable to view uploaded files on template name upload.html. This is storing uploaded files in control _ static folder, it works fine but when I click on view file in upload.html template, it is not displaying the uploaded file. Please help me to solve this. Please usermaster app: views.py: def control_upload(request): if request.method == 'POST': form = ControlForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['control_uploadfile']) model_instance = form.save() model_instance.save() else: form = ControlForm() controlmachiness = Controlmachine.objects.all() return render(request,'usermaster/control_uploadfile.html',{'form':form,'controlmachiness':controlmachiness}) def handle_uploaded_file(f): with open('usermaster/control_static/control_files/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def control_index(request): controlmachines = Controlmachine.objects.all() return render(request,"usermaster/control_show.html",{'controlmachines':controlmachines}) def control_destroy(request, id): controlmachine = Controlmachine.objects.get(id=id) controlmachine.delete() return HttpResponseRedirect('/usermaster/controlfile/') def upload(request): cmachines = Controlmachine.objects.all() return render(request,'usermaster/upload.html',{'cmachines':cmachines}) def save_machine(request): if request.method == "POST": machine_name = request.POST.get('machinename', '') operation_no = request.POST.get('operationname','') choiced_cmachine = Controlmachine.objects.filter(machine_name=machine_name, operation_no=operation_no) cmachines = Controlmachine.objects.all() return render(request,'usermaster/upload.html',{'cmachines':cmachines,'choiced_cmachine':choiced_cmachine}) models.py: class Controlmachine(models.Model): machine_name = models.CharField(max_length=100) operation_no = models.IntegerField() control_uploadfile = models.FileField(upload_to='control_files/') class Meta: db_table = "controlmachine" forms.py: class ControlForm(forms.ModelForm): class Meta: model = Controlmachine fields = ['machine_name', 'operation_no', 'control_uploadfile'] #https://docs.djangoproject.com/en/3.0/ref/forms/widgets/ widgets = { 'machine_name': forms.TextInput(attrs={ 'class': 'form-control' }), 'operation_no': forms.TextInput(attrs={ 'class': 'form-control' }), 'control_uploadfile': forms.ClearableFileInput(attrs={ 'class': 'form-control' }), } Templates/usermaster/: control_show.html: {% extends 'usermaster/home.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> … -
Deploying Django on IIS 10 but I see directory
I try deploying django app to my local server but my web application is not display. But in webbrowser is display directory, Thankenter image description here -
How to know which values are different from the existing in the database given a request.POST
I have this view (truncated) to edit existing Projects: def edit_project(request): if request.method == 'POST': project_to_edit = Project.objects.get(pk=request.POST['project_id']) form = CreateNewProjectForm(request.POST, instance=project_to_edit) if form.is_valid(): form.save() return redirect('project_page') else: return redirect('edit_project') return redirect('index') It works great, everything as expected but I would like to somehow know which fields are being updated/modified in the most pythonic way. The reason I want to know which fields are modified is to save a record in my AuditHistory model for each modified field. Ideally I would like to add the following code after the form.save() line: username = None if request.user.is_authenticated: user = request.user if user: #for each modified field, save a row into AuditHistory audit_history_entry = AuditHistory(user=user, event="Edit Project", changed_field="?", old_value="?", new_value="?") audit_history_entry.save() -
Django: Error when Retrieving data from JSONField
This is a continuation of the following question Django: Fetching data from an open source API Until now, I fetched public holiday data for France, Australia, and Germany from https://date.nager.at/ with the documentation at https://date.nager.at/swagger/index.html and stored it in a JSONField database through the /fetch_and_save application: fetch_and_save/views.py import json import requests from django.http import HttpResponse from . import models def get_public_holidays(request, year, tag): response = requests.get(f'https://date.nager.at/api/v2/PublicHolidays/{year}/{tag}') with open(f'public_holidays_{tag}_{year}.json', 'w') as outfile: json.dump(response.text, outfile) text_to_add = models.Database(data = response.text) text_to_add.save() # debug = models.Database.objects.first().data return HttpResponse('Please check the virtual environment folder for the public holidays of the assigned country.') fetch_and_save/urls.py from django.urls import path from . import views urlpatterns = [ path('<int:year>/<str:tag>/', views.get_public_holidays) ] from django.db import models class Database(models.Model): data = models.JSONField() So if I call `http://127.0.0.1:8005/fetch_and_save/2020/DE, then Django saves to my database the holidays for Germany. Now, I am trying to get another application /retrieve_from_db to get from the database the country's holidays when specifying the name of the country in the URL. Say, when I write http://127.0.0.1:8005/retrieve_from_db/Australia, I would get on the web app all the data that I have fetched from Australia without repeating years. I have started with the following /retrieve_from_db/urls.py from django.urls import path from … -
django: IntegrityError: Problem installing fixture '/app/fixtures.json': Could not load auth.User(pk=1): duplicate key
I run the fixtures locally and everything is alright. On heroku, i run heroku run python manage.py loaddata fixtures.json and it failed django.db.utils.IntegrityError: Problem installing fixture '/app/fixtures.json': Could not load auth.User(pk=1): duplicate key value violates unique constraint "users_profile_user_id_key" DETAIL: Key (user_id)=(1) already exists. i have logined with admin and delete all users and posts on heroku. what could I do? -
Django: Custom decorator to check model properties
I have a Django project in which I have a model Project that has a ManyToMany property of auhtorized_users, which uses the built-in User object: authorized_users = models.ManyToManyField(User, related_name='auhtorized_users') Now, for every view I have added a login_required decorator to test if the user is signed-in. @login_required(redirect_field_name=None) def viewproject(request, project_id): project = get_object_or_404(Project, pk=project_id) ... Working great up till here. All views are viewable only by authenticated users. Now I want to add another test to check if the currently signed-in user is also a part of the Project's authorized users, if not then give it a PermissionDenied. For this I thought I would use a custom decorator to check user's authorization. I have created the following custom decorator: def request_passes_test(test_func, login_url=None): def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): if test_func(request): return view_func(request, *args, **kwargs) else: if login_url: return redirect(login_url) else: raise PermissionDenied() return _wrapped_view return decorator And I've added this new decorator to the view to test user's authorization: @login_required(redirect_field_name=None) @request_passes_test(user_authorization_check) def viewproject(request, project_id): ... This custom decorator is similar to the built-in user_passes_test, except that it takes the request object instead of requst.user. (Learnt this from https://stackoverflow.com/a/11872933/798953). Now, In my user_authorization_check code, I'm having difficulty trying to understand … -
Django user input overrides global model
I’m new to Django and I’m creating a recipe website. I would like to have global ingredients that every user has by default, e.g bacon, eggs & etc. As well as, user created ingredients, e.g. Mom’s Sauce. Each ingredient can be assigned a category for where to find it in a grocery store, for example bacon can be found in Meat & Seafood section. What I’m struggling with is how I can allow users to change the category of a global ingredient, for example, if a user wants to change bacons category to ‘Deli’. How do I override that category for a specific user? #models.oy Ingredient(model.Models): name = models.charField(max_length=100) #e.g bacon category = models.charField(max_length=100) #e.g meat & seafood GlobalIngredient(Ingredient): pass UserCreatedIngredient(Ingredient): user = models.ForeignKey(User, on_delete=models.CASCADE) -
Django GeometryField spatial_index=False causes migration error
Previously I created a table, where one field have a geometry field for the column name geometry Here is the table class Location(models.Model): location_id = models.AutoField(primary_key=True, editable=False) location_name= models.CharField(max_length=500, blank=True, null=True) city = models.ForeignKey(City, models.SET_NULL, blank=True, null=True) state = models.ForeignKey(State, models.SET_NULL, blank=True, null=True) lat = models.FloatField() lon = models.FloatField() geom = models.GeometryField(blank=True, null=True, spatial_index=False) When I make migration command it created the migration file = worked When I migrate command it created the table in the local database However, when I tried deleting one of the field, "state" and replaced it with another field, then ran the make migration command, it created the migration file fine, But when I ran the migrate command, "geom" field raised an error that, django.db.utils.OperationalError: no such table: idx_table_name_geom. sqlite3.OperationalError: near "CONSTRAINT": syntax error The above exception was the direct cause of the following exception: that it failed to create the table in the local db. I have to put spatial_index to false because in Django it created a default srid=4326 a default index. Is there a way to address this issue, or another way to have spatial index=False because there are not that many documentation addressing how Django wants it be entered. I went … -
django.db.models.fields.related.ForeignObject.__init__() got multiple values for keyword argument 'to_fields'
I want to make relation in db without a normally _id indexing django do... I though this code should work... class Symbol_description(models.Model): symbol = models.CharField(max_length=10, null=False) description = models.CharField(max_length = 60, null=True, blank=True) class Indexes(models.Model): symbol = models.ForeignKey(Symbol_description,to_fields='symbol', on_delete=models.CASCADE) But unfortunately I am getting such an error... line 16, in Indexes symbol = models.ForeignKey(Symbol_descriptions,to_fields='symbol', on_delete=models.CASCADE) ... TypeError: django.db.models.fields.related.ForeignObject.__init__() got multiple values for keyword argument 'to_fields' -
Django: many to many filtering
queryset = Exercise.objects.all() trainer_id = filters.get('trainer_id') if 'trainer_id' in query_serializer.initial_data and trainer_id: # filter on the given trainer if and only if trainer id was provided queryset = queryset.filter(exercise_assets__trainer_id=trainer_id) I have this code in my views.py file, which generates query returning me one Exercise object as a response. Exercise object has a many to many relation (self) column defined like this: alternative_exercises = models.ManyToManyField('self', blank=True) My goal is return the initial exercise object and then filter out alternative_exercises which doesn't match alternative_exercises__assets__asset_id is equal to some value query. This is what I have so far: queryset.annotate( alternative_exercises_assets_id=FilteredRelation( 'alternative_exercises', condition=Q(alternative_exercises__assets__id=trainer_id), ), ) But it doesn't seem to work (I still get the alternative_exercises like they would be filtered in any way). Is anotate and FilteredRelation a way to go for my use case and if yes, what's wrong then? I am just learning Django and backend (writing queries!) is not something I do ofter, so sorry if my question is not formulated well. -
Django inner join to a model without directly relationship
i need to join a table without a direct relationship. models.py: class FooModel(): bar = ForeignKey(Bar) class BarModel(): pass class BazModel(): bar = ForeignKey(Bar) class QuxModel(): foo = ForeignKey(Foo) tried to reach Foo from Baz but didn't work viewset.py: def BazView(viewsets.ModelViewSet): queryset = model.BazModel.objects.all().prefetch_related('bar').prefetch_related('baz__bar') serializer_class = serializer.Baz def get_queryset(self): return self.queryset serializer.py class FooSerializer(serializer.ModelSerializer): class Meta: model = FooModel exlude = [] class BarSerializer(serializer.ModelSerializer): class Meta: model = BarModel exlude = [] class BazSerializer(serializer.ModelSerializer): foo = FooSerializer() class Meta: model = BarModel exlude = [] class QuxSerializer(serializer.ModelSerializer): class Meta: model = QuxModel exlude = [] using prefetch like that i got an error saying that Baz has no foo field. also would like to get data from QuxModel based on Foo FK... how could i perform this? -
implement collapse nav-bar using django mptt
I have started to implement Django-mptt for use in a dynamic database-driven menu. Im having an issue with how the template tags work and have just about got to grips with it. The previous site was working well with using collapse menus: although they were cumbersome to maintain they did work. The requirement is now such that I have to use data driven menus. The current site uses bootstrap to drive the collapse class - the limitation is that if the menu changes the whole menu needs some adjusting. The current site has the following: <div class="sidenav-menu-heading">{% translate 'settings' %}</div> <!-- Sidenav Accordion (Settings)--> <!-- Settings->General--> <a class="nav-link collapsed" href="javascript:void(0);" data-toggle="collapse" data-target="#SettingsGeneralviewcollapse" aria-expanded="false" aria-controls="SettingsGeneralviewcollapse"> <div class="nav-link-icon">{% icon "grid" %}</div> {% translate 'General' %} <div class="sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div> </a> <div class="collapse" id="SettingsGeneralviewcollapse" data-parent="#accordionSidenav"> <nav class="sidenav-menu-nested nav accordion" id="accordionSidenavTaskMenu"> <!-- Nested Sidenav Accordion (Settings -> Organisation)--> <a class="nav-link collapsed" href="javascript:void(0);" data-toggle="collapse" data-target="#SettingsOrgviewcollapse" aria-expanded="false" aria-controls="SettingsOrgviewcollapse"> {% translate 'Organisation' %} <div class="sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div> </a> <div class="collapse" id="SettingsOrgviewcollapse" data-parent="#SettingsGeneralviewcollapse"> <nav class="sidenav-menu-nested nav"> <a class="nav-link" href="{% url 'organisation_create' %}">{% translate 'Create' %}</a> <a class="nav-link" href="{% url 'organisation_list' %}">{% translate 'List' %}</a> </nav> </div> <a class="nav-link collapsed" href="javascript:void(0);" data-toggle="collapse" data-target="#SettingsDeptviewcollapse" aria-expanded="false" aria-controls="SettingsDeptviewcollapse"> {% translate 'Departments' %} … -
How can I get the current user when dealing with a Django InlineFormset
I've spent the better part of today looking for this answer. Long story short I'm trying to figure out how to get the current user ID that is logged in so that I can dynamically query a field and show the options available to them based on their ID. This all works well except for the part when I need their ID. I need it when they open the view, not at form save time. Here is an example of my code... Forms.py LineItemFormSet = inlineformset_factory(ParentModel, ChildModel, extra=1, fields=['line_item_cost_center','line_item_description','line_item_vendor']) class LineItemFormSet(LineItemFormSet,BaseInlineFormSet): def add_fields(self, form, index): super(LineItemFormSet,self).add_fields(form,index) form.fields['line_item_description'].widget.attrs['class'] = 'budget2' form.fields['line_item_description'].widget.attrs['placeholder'] = 'Required' qs1 = Vendor.objects.exclude(Q(is_active=False)).distinct() form.fields['line_item_vendor'].queryset = qs1 The above works just fine....However, I am trying to get the current user so that I can do something like.. Vendor.objects.filter(Q(admin_access=user)).exclude(is_active=False).distinct() I have tried various incarnations of subclassing BaseInlineFormset....But to no avail. I tried something like... class BaseFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request", None) super(BaseFormSet, self).__init__(*args, **kwargs) and then I did something like... LineItemFormSet = inlineformset_factory(ParentEntity, ChildEntity, formset=BaseFormSet, form=ChildForm, extra=1) formset = LineItemFormSet(form_kwargs={'request': request}) And then I kept getting an error that says that request is not found. My View looks like... class CreateLineItemView(LoginRequiredMixin,CreateView): model = NewLineItem form_class = CreateLineItemForm …