Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to clear cache for Django with Docker?
I have a Django project that I am using with memcached and Docker. When I use sudo docker-compose up in development I'd like the entire cache to be cleared. Rather than disabling caching wholesale while in development mode, is there a way to run cache.clear() as noted in this question on each re-run of sudo docker-compose up? I am not sure whether this should go in: docker-entrypoint.sh Dockerfile docker-compose.yml Somewhere else? -
How to display column names in Django template without knowing them ahead of time?
I have a queryset that I am passing to Django. There are 100 columns or so. I want to render this single object as either an HTML list without knowing all the column names. I know I could use ListView, but I want more control to do something like this within a TemplateView (with additional graphs): <ul> {% for obj in queryset %} <li> {% for column in obj %} [Name of Column]: {{ column }} {% endfor %} </li> {% endfor %} </ul> So I want to render both the name of the column and the column data without knowing the name of the column beforehand. Ordinary I'd do this: <ul> {% for obj in queryset %} <li> Column 1: {{ obj.column1 }} Column 2: {{ obj.column2 }} ... Column 100: {{ obj.column100 }} </li> {% endfor %} </ul> But this is a bit tedious and requires writing out each column name by hand. -
Django DRF role level permission
I have developed API's using DRF. I am struggling to relate the authorization part from Django's default permission which we define in the admin section for each and every role to the API. Let's say I have two API's Customer Management and Customer Sales and have two roles created from them at the Django admin portal. manager role will only manage customer (add, view, delete and update) whereas sales role will manage sales (add, view, delete and update) for every customer. When I try testing them in the admin portal the permissions work fine. The corresponding role has corresponding access. If I use the same with REST API it fails to comply with permission which is defined in the backend. It is like both the roles are able to access both the API's. How do I handle this? Should I implement my own permission system ignoring old one (auth_permission, auth_group_permissions,auth_user_user_permissions) used in Django or is there any workaround to use Django permissions to make this work? -
Django - Select items and quantity from pre-created list
I cannot figure out a suitable solution for what I believe is a beginner problem. Any help is highly appreciated. The website I am building will be used to plan parties. Two types of people will use it, party organizers and party visitors. The party organizers are able to create a party and select items to be offered to visitors. Items are food and drinks, 1 item = one pizza or one beer. Users will then be able to confirm participation for the party and select which food and drinks they would like to order and how many. I already created authentication and creation of a party. Now, my issues are this: How can the organizer create a list of items to be offered to the visitor? How can the visitor select both type of item and quantity? I have tried with the following code (trimmed down): models.py: class ItemType(models.Model): """Create items (food and drinks).""" name = models.CharField() class Party(models.Model): """Create a party.""" organizer = models.ForeignKey(User) party_name = models.CharField() items_to_be_offered = models.ManyToManyField(ItemType) class PartyRegistration(models.Model): """Register for a party / create party registration.""" party = models.ForeignKey(Party) visitor = models.CharField() selected_items = models.ManyToManyField() class ItemSelection(models.Model): """Specify which items and number of items … -
Django - ClearableFileInput dont clear
I'm folowing a tutorial to make a public profile in Django, but i have troubels with the ClaerableFileInput. It's not clearing the image, and I don't know why. Let me show you the code: models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='profiles', null=True) empresa = models.CharField(max_length=200, null=True, blank=True) area = models.CharField(max_length=200, null=True, blank=True) forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['avatar','empresa','area'] widgets = { 'avatar': forms.ClearableFileInput(attrs={'class':'form-control-file mt-3'}), 'empresa': forms.TextInput(attrs={'class':'form-control-file mt-3', 'placeholder':'Empresa'}), 'area': forms.TextInput(attrs={'class':'form-control-file mt-3', 'placeholder':'Area'}), } views.py @method_decorator(login_required, name='dispatch') class ProfileUpdate(UpdateView): form_class = ProfileForm success_url = reverse_lazy('profile') template_name = "registration/profile_form.html" def get_object(self): profile, created = Profile.objects.get_or_create(user=self.request.user) return profile profile_form.html {% extends 'core/base.html' %} {% load static %} {% block title %}Perfil{% endblock %} {% block content %} <style>.errorlist{color:red;} label{display:none}</style> <main role="main"> <div class="container"> <div class="row mt-3"> <div class="col-md-9 mx-auto mb-5"> <form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{form.as_p}} </form> </div> </div> </div> </main> {% endblock %} Render <div class="container"> <div class="row mt-3"> <div class="col-md-9 mx-auto mb-5"> <form action="" method="post" enctype="multipart/form-data"><input type="hidden" name="csrfmiddlewaretoken" value="H1BbxtduaemnAyRktgLpZizjuEbxjOUFu9A7g3Tl1pQb6THvLFoWcLE3fhWvCycu"> <p><label for="id_avatar">Avatar:</label> Actualmente: <a href="/media/profiles/Rami_Oli.png">profiles/Rami_Oli.png</a><br> Modificar: <input type="file" name="avatar" class="form-control-file mt-3" accept="image/*" id="id_avatar"></p> <p><label for="id_empresa">Empresa:</label> <input type="text" name="empresa" class="form-control-file mt-3" … -
---------TypeError: tuple indices must be integers or slices, not str----------
self.fields['titles'].queryset = Title.objects.filter(type=x) TypeError: tuple indices must be integers or slices, not str x =Asset_Type.objects.get(asset_id=1) print(x) a = Title.objects.get(type=x) print(a) self.fields = ("titles",) self.fields['title'] = Title.objects.filter(type=x) y= Album.objects.filter(titles=Title) print(y) -
django_saml2_auth not able to configure /saml2_auth/acs/
I am using django_saml2_auth plugin in my django app. When trying to configure the access-point for the config in our identity provider I get the following error message: Sorry, you are not allowed to access this app when calling http://MY_URL/saml2_auth/acs/ and directly redirected to /saml2_auth/denied/ My config looks like: SAML2_AUTH = { 'METADATA_AUTO_CONF_URL': 'https://xxxx.xxxx.com/FederationMetadata/2007-06/FederationMetadata.xml', 'DEFAULT_NEXT_URL': '/core', 'CREATE_USER': True, 'NEW_USER_PROFILE': { 'USER_GROUPS': ["user"], # The default group name when a new user logs in 'ACTIVE_STATUS': True, # The default active status for new users 'STAFF_STATUS': False, # The staff status for new users 'SUPERUSER_STATUS': False, # The superuser status for new users }, 'ATTRIBUTES_MAP': { 'email': 'Email', 'username': 'UserName', 'first_name': 'FirstName', 'last_name': 'LastName', }, 'ASSERTION_URL': MY_URL, 'ENTITY_ID': '%s/saml2_auth/acs/' % MY_URL } -
Django admin inline unique constraint violation on edit
I have a form with inline. A related model has a unique together constraint (parent_id, number). I have an entity with two children parent_id | number | 1 | 1 | 1 | 2 | and I am trying to edit these children in one operation to the state parent_id | number | 1 | 2 | 1 | 3 | When I am saving I have an error on the first entry: Child with this parent_id and number already exists. However, if I firstly edit the second entry: parent_id | number | 1 | 1 | 1 | 3 | and then the first parent_id | number | 1 | 2 | 1 | 3 | in two separate actions, it works fine. ParentAdmin definition class ParentAdmin(admin.ModelAdmin): form = BaseForm inlines = [LevelExerciseInline] ChildInline definition class ChildInline(admin.StackedInline): form = BaseForm model = Child extra = 3 -
Django and docker: Should we use python virtualenv
I am thinking to use a docker for django. Since this docker image will be exclusive for a particular django project is it ok to just pip install everything in docker rather than creating a virtualenv and then install all the required django and related packages using pip So what is the best way and also safe way if one want to stick to docker for django projects. -
Replacing ManyToMany relationship in django
How can I replace ManyToMany relationship in django with something else . I heard about multiple select field or multiple choice field module that we can install it with pip. Is it true? If it is true how can I use it? And if there are other ways can you tell me? -
Unable to find cause of 403 Forbidden error: Nginx Daphne Django
I have had confirmation in another question that I can indeed run a Django app using only Nginx and Daphne and have modified my nginx config code as per their suggestion. The application is running with Daphne on 127.0.0.1:8001 However, I am running into a 403 Forbidden error. The nginx error logs say: "2019/03/07 11:23:48 [error] 16642#16642: *11 directory index of "/path/to/app" is forbidden, client: xx.xxx.xx.xx, server: app.com, request: "GET / HTTP/1.1", host: "www.app.com", referrer: "http://www.app.com"" I'm still facing a 403 and would be grateful to anyone who may be able to locate where the problem is coming from. My nginx config upstream socket { ip_hash; server 127.0.0.1:8001 fail_timeout=0; } server { listen 80; #listen [::]:80 ipv6only=on; server_name your.server.com; access_log /etc/nginx/access.log; root /var/www/html/someroot; location / { #autoindex on; # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. # try_files $uri =404; #proxy_set_header X-Real-IP $remote_addr; #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #proxy_set_header Host $http_host; #proxy_set_header X-NginX-Proxy true; #proxy_pass http://socket; #proxy_redirect off; #proxy_http_version 1.1; #proxy_set_header Upgrade $http_upgrade; #proxy_set_header Connection "upgrade"; #proxy_redirect off; #proxy_set_header X-Forwarded-Proto $scheme; #proxy_cache one; #proxy_cache_key sfs$request_uri$scheme; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/some/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/some/privkey.pem; … -
Make related articles feature with python and django or react
I have a blog website backend is Python + Django + DRF. On frontend I have React. At the article page I want to have "related articles" section and "popular articles". The same I want to have for the root page. For me is so important that these sections will be "user specefic". For example if user have been reading a lot about "France" it would influence to recommended articles and this topic will have more weight than other. How can I do that? Can I do that with python? What technology should I use? Thank you! -
How to create floors and rooms an hostelmanagement system using Django
I am attempting a Hostel Management system using Django. The system can allow a user to register tenants and assign them a room on a specific floor. I want to create a hostel in the django-admin with 5 floors, and each floor has 50 rooms. How can I add the floors and rooms to the models.py? I am not that well experienced with Django, your responses will really help me learn a lot. -
How to use settings.configure() to use specific app settings
I'm trying to use django within a python shell and am restricted so that I can't change environment variables - ie so can't set DJANGO_SETTINGS_MODULE Instead I tried to use settings.configure() but can't get it to pick up my apps settings. My project is laid out as (missing out the non important parts) my_project ---config -------settings ----------common.py ----------local.py ----------prod.py manage.py -
Django {{ request.build_absolute_uri }} return 127.0.0.1
Django version: 2.1.5 uWSGI "{{ request.build_absolute_uri }}" return http://127.0.0.1:8888/ I want to get a domain url not a ip adress... Thanks -
Django UpdateView initial parameter passed to other UpdateView's
I have two update views accessed with different urls. In the first update view CreateType I set a variable in my initial called old_type. After I submit and go through other views I end up in my second UpdateView CreateSchedule. if i print self.initial in my second view I find the var old_type I have set in my first UpdateView for some reason. First view class CreateType(views.UpdateView): """ Create type form """ model = Group form_class = TypeForm template_name = 'create.html' extra_context = {'has_fifth_steps': False, 'active_step': 1, 'progress': 0} def get_object(self, queryset=None): object = super(CreateType, self).get_object(queryset) self.initial['old_type'] = object.type return object def form_valid(self, form): object = form.save() if object.type == Group.TYPE_SINGLE and self.initial['old_type'] == Group.TYPE_MULTIPLE: first_obj = Obj.objects.filter(group=object).values('id').first() if first_obj: Obj.objects.filter(group=object).exclude(id=first_obj['id']).delete() return redirect('create_obj.debtor', pk=object.pk) My second view: class CreateSchedule(views.UpdateView): """ Schedule form """ model = Group fields = [] template_name = 'createschedule.html' def get_object(self, queryset=None): object = super(CreateSchedule, self).get_object(queryset) # if object.type == Group.TYPE_SINGLE: self.obj_object = Obj.objects.filter(group=object).first() return object def get_form(self, form_class=None): paymentschedule_formset = modelformset_factory( model=PaymentSchedule, form=PaymentScheduleForm, fields=('due_date', 'value'), validate_min=True, min_num=self.obj_object.number_of_payments, validate_max=True, max_num=self.obj_object.number_of_payments, ) print(self.initial) return paymentschedule_formset( queryset=PaymentSchedule.objects.filter(obj=self.obj_object), ) def get_context_data(self, **kwargs): context = super(CreateSchedule, self).get_context_data(**kwargs) if self.object.type == Group.TYPE_MULTIPLE: context['has_fifth_steps'] = True context['active_step'] = 5 else: context['has_fifth_steps'] = False … -
How can i reduce the table width or make the table responsive for chrome?(Django/Python deployed web-app)
IOS chrome browser Laptop chrome browser <!---To Display Timetable Entries-----> <div class="container"><br> <span style="font-family:'Futura';font-weight:bold;"><h2>TimetableMatch</h2></span> <hr> <div style="overflow-x:auto;"> <table class="table table-dark"> <thead> <tr> <th>Module</th> <th>Day</th> <th>Time</th> <th>Area</th> <th>Actions</th> </tr> </thead> <tbody> {% for entry in entrys %} <tr> <td>{{ entry.module }}</td> <td>{{ entry.day }}</td> <td>{{ entry.time }}</td> <td>{{ entry.location }}</td> <td><a class="btn btn-info" href="../edit/{{ entry.id }}">Edit</a> <br> <br> <a class="btn btn-danger" href="../delete/{{ entry.id }}">Delete</a> </td> </tr> {% endfor %} </tbody> </table> </div> <div class="row"> <div class="col-md-4 col-lg-2"> <a class="btn btn-primary" href="../add_entry/">Add Timetable Entry</a> <br> <br> <a href="{% url 'homepage' %}"> <button type="button" class="btn btn-primary btn-xs"> Back to home</button></a> <a href="{% url 'index' %}"> <br> <br> <button type="button" class="btn btn-primary">Logout</button> </a> </div> </div> </body> This is the code for the page that is being viewed in those images, is there any changes that need to be made to make it more responsive in a mobile chrome browser? -
Why doesn't Django see the function
There is such a function: def getNearestNotes(request, longitude, latitude): if request.method == 'GET': c = connection.cursor() r = None try: c.callproc('GetAllNotes', (float(longitude), float(latitude))) r = c.fetchall() finally: c.close() return HttpResponse(str(r)) else: return HttpResponse('needGetMethod') It should call such a function in the postgresql database: create function "GetAllNotes"(long numeric, lat numeric) returns TABLE ( UserId integer, UserName character varying, NoteName character varying, NoteLong double precision, NoteLat double precision ) language plpgsql as $$ BEGIN RETURN query (SELECT Notes."UserId", Users."Name", Notes."Name", Notes."Longitude", Notes."Latitude" FROM Notes INNER JOIN Users ON Notes."UserId" = Users."Id" WHERE (point(long, lat) <@> point(Notes."Longitude", Notes."Latitude") <= 0.124274)); END $$; alter function "GetAllNotes"(numeric, numeric) owner to postgres; But when calling this function, django gives an error - function getallnotes(numeric, numeric) does not exist LINE 1: SELECT * FROM GetAllNotes(28.0,23.0) HINT: No function matches the given name and argument types. You might need to add explicit type casts. The base is connected. But if I do this - c.execute("SELECT routine_name FROM information_schema.routines WHERE routine_type='FUNCTION' AND specific_schema='public'") r = c.fetchone() - then the 'GetAllNotes' function will be listed -
django render to pdf with button
I have def that render to pdf with action on django-admin. def Print(self, request, obj): data = { 'obj':obj } pdf = render_to_pdf('daa/imprimir/pdf.html', data) if pdf : response = HttpResponse(pdf, content_type='application/pdf') filename ="Avaria_%s.pdf" %("123451231") content = "inline; filename='%s'" %(filename) response['Content-Disposition'] = content download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") and on my actions i have: class ModelAdmin(admin.ModelAdmin): actions = [Print] and it is working all good, i select what objects i want to render and in my html i have cicles that make a list of all fields i want of those obj's. But right now i dont want to render to pdf a list i want to render only 1 obj. So i create a custom button to do that. http://prntscr.com/muijhl So when i click on button i want to render to pdf the obj wich is open. Dont know what i need to do , to take my def and but inside of button -
Django Server inside another program
I wrote a Django app that collects data from clients and displays them in it's web app. Now I want to write a script/program (WPF or a small Java App) that manages the Django server. Things like Start/Stop, update Django files, migrate Data etc. Reason is: I want to stuff all of that into an .exe, maybe with a setup and licensing for my potential customers. What would be the most professional attempt to do this? I wrote smaller scripts before and built them with pyInstaller, which does not seem to work with Django. Or should I just install a python interpreter with my setup and just run the python files? Then my code would be visible to my customers. Any tips are appreciated. -
django malformed array literal:
i have a little problem: i have this model: class myModel(models.Model): myField =JSONField() i want to update this field: data={'rda': {'punti': 0, 'rank': 1, 'pos': 'eq'}} myModel.myField=data data.save() but i have this error: Traceback (most recent call last): File "/home/hy0/.conda/envs/ciclods_env/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.DataError: malformed array literal: "{"rda": {"punti": 0, "rank": 1, "pos": "eq"}}" how can i solve it? -
How to send selected option value in form action in django
<form name="move_form" action="{% url index %}move_review/" method="post"> <select name="to_lst"> {% if list1 %} {% for l in list1 %} <OPTION value={{ l.id }}>{{l.name }}-{{ l.age }}</OPTION> {% endfor %} {% else %} <OPTION> None </OPTION> {% endif %} </select> <INPUT type="submit" value="Accept" ><INPUT type="Reset"> i want to send the l.id value in the action which i will match in urlconf. what i want is to make the url like /move_review/{l.id}/ I am a newbie in django. Any help will be highly appreciated. Thanks. -
NullBooleanField values not mapping correctly
I have a ModelForm taking a secondary instance as a template to fill in the form with initial values: class MyForm(forms.ModelForm): def __init__(self, template_instance=None, *args, **kwargs): if template_instance: kwargs['initial'] = model_to_dict(template_instance) super(MyForm, self).__init__(*args, **kwargs) Now, my model has a NullBooleanField "enable", which I expect to be set to whatever value the template instance has, when the form instance is set at the last line where the base constructor is called. You can see that if template_instance has that field as True, kwargs initial is updated accordingly: {'initial': {'enable': True, 'master': False, u'id': 103, 'name': u'test'}} However when the form instance is set, that field has the value of False instead: self.instance.__dict__ Out[2]: {'id': None, 'master': False, 'name': u'test', 'subscores_enabled': False} I tried to set the value based on the values mapped by the widget (2 for True and 3 for False): kwargs['initial']['subscores_enabled'] = '2' if self.template_instance.subscores_enabled else '3' (tried also with ints instead of strings) But it was all the same. What am I supposed to do? -
Getting form data in Django middleware
I am trying to get use entered data into form in my middleware so I can track the users activity. I tried doing it but it is not working. Whats wrong ? Below is my html and my middleware: middleware.py: def __call__(self, request): response = self.get_response(request) if request.method == "GET": f = open("--my-file-path--", 'a') f.write("User clicked ") name = request.GET.get('name') if not name == 'None': f.write(str(name)) f.write("\n") f.close() elif request.method == 'POST': f = open("--my-file-path--", 'a') f.write("User clicked ") if request.POST.get("Login"): nm = request.POST.get("Login") if not nm == 'None': f.write("Login\n") elif request.POST.get("Authorize"): f.write("Authorize\n") form = AuthUserCheckbox(data=request.POST, user=request.user) if request.choice.is_valid(): ch = form.cleaned_data['choice'] f.write("User then chose ") f.write(ch) html: {% extends 'todoapp/base.html' %} {% block title %}Authorize users{% endblock %} {% block content %} <h2>Select users to authorize</h2> <form method="post" action="{% url 'auth_users' %}" id="authorise_users"> {% csrf_token %} {{ form.choice }} <br/><input type="submit" value="Authorize" name="Authorize"> &nbsp;&nbsp;<button onclick="location.href='{%url 'dashboard' %}?name=Go back'" type="button">Go back</button> </form> {% endblock %} -
Insert Web Api rest Values (Json return) into html form (Get method)
I'm trying to insert a get method in my html page (Body.onload) that actually full some form fields from this json web api result automaticly. I'm looking for several answers, but none of then seens clear to me. I checked out angularJS, Django, Html bindign, but i feel like lost in this one. Could anyone give me a north? Thanks in advance, Daniel. My form: <form method="get" id="form" name="form" enctype="application/json" onsubmit="return checkForm(this)" action="/api/Business_Register"> CNPJ: <input type="number" name="BusinessRegister" placeholder="Insira o número do CNPJ" required style="background-color:#292a60; width:100%" /> SENHA: <input type="password" name="Password" placeholder="Insira a senha (mínimo de seis dígitos)" required style="background-color:#292a60;width:100%" /> CONFIRME A SENHA: <input type="password" name="ConfirmPassword" placeholder="Confirme a senha" required style="background-color:#292a60;width:100%" /> Razão Social: <input type="text" name="BusinessName" placeholder="Insira o nome da empresa" required style="background-color:#292a60;width:100%" /> Nome Fantasia: <input type="text" name="BusinessFantasyName" placeholder="Insira nome fantasia da empresa" required style="background-color:#292a60;width:100%" /> Área: <input list="Area1List" id="Area1Field" name="BusinessArea" placeholder="Insira a área de atuação da empresa" required style="background-color:#292a60;width:100%" /> <input type="hidden" id="BusinessSpecificArea" name="BusinessSpecificArea" placeholder="Insira a área especifica da empresa" style="background-color:#292a60;width:100%" /> País de Atuação: <input type="text" name="Country" placeholder="Insira o país de localização de seu estabelecimento" required style="background-color:#292a60;width:100%" /> Estado: <input type="text" name="State" placeholder="Insira o estado de localização de seu estabelecimento" required style="background-color:#292a60;width:100%" /> Cidade: <input type="text" …