Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.OperationalError: could not connect to server: Connection refused DJANOG gitlab CI
I am trying to run django test on CI gitlab but getting this error : django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? whilt my yml file is like stages: - test variables: POSTGRES_DB: asdproject POSTGRES_USER: runner POSTGRES_PASSWORD: asdpassword test: type: test script: - whoami - export DATABASE_URL=postgres://runner:asdpassword@postgres:5432/asdproject - apt-get update -qy - apt-get install -y python3-dev python3-pip - pip3 install -r requirements/base.txt - python3 manage.py test how I can connect postgresql here ? -
Python Django 3.0 URL problem, the browser adds an / at the end
I am new to programming and try to build a website with django 3.0 and Python 3.8.0 (64 bit) My question is why is it that the in the browsers (chrome and edge) wenn I enter http://127.0.0.1:8000/about it automatically adds an / at the end so it becomes http://127.0.0.1:8000/about/ Wenn I enter http://127.0.0.1:8000/services it works fine and shows the page. This is a problem because the extra / results in an error Page not found (404) Please help I am stuck in my learning -
gunicorn + nginx suddenly started to show 502 Bad Gateway
My set up worked stable and nicely for about 1 and a half month. I installed https://pypi.org/project/django-ipware/ with the following commands: pip install django-ipware - it installed for python 2.7 pip3 install django-ipware - I need django-ipware for python 3.6 I stopped and started gunicorn and nginx... My app still didn't see django-ipware... I forgot to switch off both gunicorn and nginx and restarted the server with the reboot command. After reboot, the site gives me 502 Bad Gateway... I deleted django-ipware app, it didn't help and I think my fault was at the hard reboot... What I noticed so far: My sc.sock file is not created on the start of gunicorn and nginx in the right location, which is: /home/evgeny/sc_project/sc.sock it is just not there... Despite I have right permission for the right person and right group: drwxrwxr-x 5 evgeny nginx 85 Oct 28 18:37 sc_project Instead gunicorn.sock always sits (even if gunicorn and nginx not activated) at the /run location. Like so: /run/gunicorn.sock As I understand it is default location, for some tutorials for gunicorn and nginx set up... Also, when I stop both engines, I have: [root@ [~]]# systemctl stop gunicorn Warning: Stopping gunicorn.service, but it can … -
How to import a variable from django into vue.js
I want to import a variable from a django generated html page into my App.vue component. My goal is to pass a String, which represent the user AuthGroup, eg. 'milkman', 'hairdresser' or 'supplier' The error Message looks like this: Module parse failed: Unexpected token (1:1) You may need an appropriate loader to handle this file type, currently no loaders are configured to > process this file. See https://webpack.js.org/concepts#loaders {% extends 'base.html' %} | {% load render_bundle from webpack_loader %} | {% load navtag %} frontend.html {% extends 'base.html' %} {% load render_bundle from webpack_loader %} {% load navtag %} {% block head %} <title>title</title> <script> const test = "{{ auth_group }}" // variable/string needed in App.vue </script> {% endblock %} [...] {% block content_vue %} <div id="app"> <app></app> </div> {% render_bundle 'app' %} {% endblock %} I can't figure out how to modify webpack or find a way to import the variable from django into the vue project. FYI: The vue project is a small part of a large Django environment. -
How to secure my files from my clients in django? [closed]
i created an app in django and using it on local server for right now. In this app client can upload the files. But the problem is that i don't want anyone to access the directory where my files are stored. I want my files to be stored in such a way that no body can delete, copy and edit that.How can i do it? -
Django migrations foreign key mismatch with legacy database
Hej all, I am trying to integrate a SQLite legacy database with Django v3.1.2, and so far it's pretty painful (new to django, so apologies if it's sth obvious). I assume something is wrong with my database schema or with the migration process. So here is what I did and my problem: I have run inspectdb on my legacy database and cleaned up the models, leaving me with the following two models (there are more models in my application, but these are the ones apparently causing a problem): class Integrons(models.Model): arg = models.ForeignKey('Args', on_delete=models.CASCADE) int_id = models.IntegerField(primary_key=True) int_start = models.IntegerField() int_stop = models.IntegerField() int_complete = models.CharField(max_length=500) class Meta: managed = False db_table = 'integrons' class IntElements(models.Model): int = models.ForeignKey('Integrons', on_delete=models.CASCADE) el_id = models.IntegerField() el_start = models.IntegerField() el_stop = models.IntegerField() el_name = models.CharField(blank=True, null=True, max_length=500) el_strand = models.CharField(blank=True, null=True, max_length=500) class Meta: managed = False db_table = 'int_elements' The respective fields in my legacy database are: Integrons: arg_id, int_id, int_start, int_stop, int_complete IntElements: int_id, el_id, el_start, el-stop, el_name, el_strand As seen in the models, IntElements.int_id should refer to Integrons.int_id. Now I am trying to migrate everything - running python manage.py makemigrations works fine. However, when running python manage.py migrate , I … -
How can i solve The QuerySet value for an exact lookup must be limited to one result using slicing. Django
I want to catagorize my posts. def katagori_girisim(request): cg = IlanKatagoriGirdi.objects.filter(katagoriler='Girisimci Mentorlugu') katagiri = IlanSayfa.objects.filter(ilan_katagori=cg) return render(request, 'pages/katagori_girisim.html', {'katagiri':katagiri}) I wrote this code in view. And I wrote this in template: {% for girisimilan in katagiri %} <div class="card"> <img src="/media/{{ girisimilan.ilan_foto }}" class="card-img-top img-fluid" style="width: 25rem; height: 15rem;" alt="ilan_foto"> <div class="card-body"> <h5 class="card-title text-center">{{ girisimilan.ilan_baslik }}</h5> <p class="card-text text-center">{{ girisimilan.ilan_aciklama }}</p> </div> </div> {% endfor %} But I am getting the error in the title. How can i solve this problem? -
add user_id attribute in AuthenticationMiddleware | Django
I have a following question regarding Django authentication middleware: class AuthenticationMiddleware(MiddlewareMixin): def process_request(self, request): assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ) request.user = SimpleLazyObject(lambda: get_user(request)) As you can see here middleware calls method get_user from backend (in my case simple_jwt) and puts this method in a SimpleLazyObject in order to evaluate later. def get_user(self, validated_token): """ Attempts to find and return a user using the given validated token. """ try: user_id = validated_token[api_settings.USER_ID_CLAIM] except KeyError: raise InvalidToken(_('Token contained no recognizable user identification')) try: user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id}) except User.DoesNotExist: raise AuthenticationFailed(_('User not found'), code='user_not_found') if not user.is_active: raise AuthenticationFailed(_('User is inactive'), code='user_inactive') return user What I want to do is to keep request.user = SimpleLazyObject(lambda: get_user(request)) in order to provide user instance for apps that uses it but for my custom apps I want to add something like pseudocode request.user_id = user_id from user (user_id = validated_token[api_settings.USER_ID_CLAIM]) in order to not query database each and every request for user object in case I need only user_id which I already have directly in get_user method in backend. Question – how to … -
Django CSV and data output
Have been trying to put something together which takes an uploaded csv file of all employees data from the previous day, this includes quite a few different columns such as name, rate , up and downtime. This will be added to each day, to build the database, I have looked into a few different ways to then output that data in a user friendly way where you can see each employee data over the past week month year etc could someone please recommend the best way to implement this? I have so far looked into Charts.JS and read through some documentation. Not even sure if python or django are the best route for this application. -
I am getting an error in django project while submitting the form can any one please tell the correction of my error
Error Page not found (404) Request Method: POST Request URL: http://localhost:8000/contact/contact Using the URLconf defined in portfolio.urls admin/ [name='home'] about/ [name='about'] projects/ [name='projects'] contact/ [name='contact'] The current path, contact/contact, didn't match any of these. **code for the form ** <form action="contact" method="POST"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="Your Name"> </div> <div class="form-group"> <label for="email">Email address</label> <input type="email" class="form-control" id="email" name="email" placeholder="name@example.com"> </div> <div class="form-group"> <label for="phone">Phone Number</label> <input type="phone" class="form-control" id="phone" name="phone" placeholder="Your Number"> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Explain your concern</label> <textarea class="form-control" id="desc" rows="3"></textarea> </div> <button type="submit" class="btn btn-success">Submit</button> </form> views.py def contact(request): return render(request,"contact.html") urls.py this url is from my app urlpatterns=[ path("",views.home,name="home"), path("about/",views.about,name="about"), path("projects/",views.projects,name="projects"), path("contact/",views.contact,name="contact"), ] urls.py this url is from my project urlpatterns = [ path('admin/', admin.site.urls), path("",include("home.urls")), ] -
Admin user specified python code to be executed as API later
Working on a webapp for a client. They want to be able to specify a function in Python that will calculate an end result based on end user inputted parameters. Is it possible to store their code (saved from a text field in an admin panel) and execute it later as an API (django or flask), with the relevant parameters (provided by the end user, ie not admin) at runtime? Or any better way to handle that? -
Still recognize my null input field as same exist error
Cannot change the Django field from mandatory to optional input I have a sign up form that requires the users to fill in their phone number. Now ,I want to change it from mandatory to optional .But it fails and still recognizes my phone number null input as '#phone_exist_error' .How to fix? view.py def signup(request): username=request.POST.get('username') email=request.POST.get('email') password=request.POST.get('password') phone_no=request.POST.get('phone_no') .... if Signup.objects.filter(username=username).exists(): return HttpResponse("user_name_exists") elif Signup.objects.filter(email=email).exists(): return HttpResponse("email exists") # I have commented these code already! # elif Signup.objects.filter(phoneno=phone_no).exists(): # return HttpResponse("phone exists") else: if dob: user_obj=Signup(username=username,email=email,password=password,phoneno=phone_no,dob=dob,gender=gender,profile_image=profile_img,email_status=email_all,pwd_status=phone_all,bio=bio) user_obj.save() else: user_obj=Signup(username=username,email=email,password=password,phoneno=phone_no,gender=gender,profile_image=profile_img,email_status=email_all,pwd_status=phone_all,bio=bio) user_obj.save() ... return HttpResponse("success") Register.html var form = $("#form_data")[0]; var data_item = new FormData(form); data_item.append("profile_img",document.getElementById("imgInp").files[0]) data_item.append("username",username) data_item.append("password",password) data_item.append("cnf_password",cnf_password) data_item.append("email",email) data_item.append("phone_no",phone_no) ... $("#loading").show() $.ajax({ method : "POST", url : "/signup/", enctype : "mutipart/form_data", processData : false, contentType : false, cache : false, data : data_item, success : function(response){ console.log(response) $("#loading").hide() if (response == "success") swal("Registration Saved Successfully", { icon: "success", button: "Ok", closeOnClickOutside: false, }).then(function() { location.href = "/signin/"; }); else if (response == "email exists"){ $('#error_email_exists').show(); $('#email').focus(); } <!-- null input but activate this --> else if (response == "phone exists"){ $('#phone_exist_error').show(); $('#phone_no').focus(); } else if (response == "user_name_exists"){ $('#error_name_exists').show(); $('#username').focus(); } } });... $('#phone_no').keyup(function(){ $('#phone_no_error').hide(); $('#phone_exist_error').hide(); }) -
ManyToMany in Form_valid
I have 2 models that are related to ManytoMany class Prestaciones(TimeStampedModel): nombre = models.CharField('Prestanciónes', max_length=35) prestacion = models.ManyToManyField(PrestacionIndi) turno = models.ForeignKey(Turno, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) activo = models.BooleanField(default=True) class PrestacionIndi(TimeStampedModel): nombre = models.CharField('Prestanción', max_length=35) num_dias = models.IntegerField('Dias',) user = models.ForeignKey(User, on_delete=models.PROTECT) activo = models.BooleanField(default=True) View: class PrestacionesCreateview(FormView): template_name = 'admins/form_prestaciones.html' form_class = PrestacionesForm success_url = reverse_lazy('admins_app:prestaciones') def form_valid(self, form): nombre = form.cleaned_data['nombre'] prestacion = form.cleaned_data['prestacion'] turno = form.cleaned_data['turno'] user = self.request.user obj, created = Prestaciones.objects.get_or_create( nombre = nombre, user = user, prestacion = prestacion, turno = turno ) return super(PrestacionesCreateview, self).form_valid(form) When making a save, it marks an error since it cannot save several values. I think my problem would be in the form_valid area since it is only receiving a value and it is not iterating the values -
How to make my Django API public, which is connected to MYSQL database?
The problem is I have connected my Django API to MYSQL workbench, but it is only accessible in my localhost. Methods I have tried: Forwarding a port and running my server with "python manage.py runserver 0.0.0.0:3000", which worked, and the API was made public in my another Django API project without MYSQL connection but not working in the one connected to MYSQL. I hosted my Django API in PythonAnywhere. Now my API became public, but I could not connect my Django API with MYSQL. Please help me with it. Thanks in advance -
WARNINGS: ?: (mysql.W002)
I'm new to django, just wanted to change to MySQL databases, but this warning keeps how up even though I have already added the code for it. My setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "mysql_database", "USER": "root", "PASSWORD": "", "OPTION": { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES', innodb_strict_mode=1", 'charset': 'utf8mb4', "autocommit": True, } } } The warning WARNINGS: ?: (mysql.W002) MariaDB Strict Mode is not set for database connection 'default' HINT: MariaDB's Strict Mode fixes many data integrity problems in MariaDB, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/3.1/ref/databases/#mysql-sql-mode Have tried resetting and migrating a couple of times, and it didn't work. -
After an upgrade from Django 1.11 to Django 3.1 django admin shows list of models on top of internal items
After an upgrade from Django 1.11 (python2.7) to Django 3.1 (python3.6) on Centos7, django admin still shows the list of models on top of the page, above the list of items in this model. Before the upgrade, the admin showed everything correctly: you see a list, you enter an item and see a screen related to this item, no more lists. Please see the related screenshots: Please advise how to solve this. -
Django Modelforms: how to show a select for a CharField?
I'm using ModelForms in Django to create my form. This works well. However, there is a field that is a charfield in the database, but for a particular form I want to restrict the options that users can enter to a list of specific items - ideally shown in a <select>. What would be the right way to do this? Here is my code: form = ModelForm(request.POST or None, instance=info) In my models: class Street(models.Model): name = models.CharField(max_length=255) I have tried the following: from django import forms CHOICES = [('1', 'First'), ('2', 'Second')] choice_field = forms.ChoiceField(widget=forms.Select, choices=CHOICES) form.fields["street"].widget = choice_field Which gives this error: 'ChoiceField' object has no attribute 'attrs' -
Django Template Is Not Updating the Selected Option
I have been working on this template where I need to show the options (showing the list of companies using for loop) for selection. <select id="company_id" name="company_id"> <option selected="selected">(없음)</option> {% for company in company_list %} <option value="{{company.id}}"> {{company.name}} </option> {% endfor %} </select> On the template it looks like this: the actual template default option the dropdown options Let's say I picked the 6th option (2nd from the bottom). I want the default option to be changed VISUALLY when I hide the dropdown, clicking somewhere else. However, the selected option does not show visually. It goes back to that very first option Strangely, however, when I click on the selection to view the dropdown list, I see that the one I clicked is selected, though it is vague. The 6th option is colored whereas unselected ones are black Is there any way to make it show the one selected? My user complains that it is very confusing to keeping seeing the first option only even after selecting something else. One thing I tried is getting rid of 'selected="selected"' snippet like so: <select id="company_id" name="company_id"> <option>(없음)</option> {% for company in company_list %} <option value="{{company.id}}"> {{company.name}} </option> {% endfor %} </select> However, … -
Django Admin how to show ID of Items in List
Here is what i see in my Django Admin: The model Topic has 4 fields in it. class TopicModel(models.Model): strid = models.CharField(max_length=200, unique=True) name = models.CharField(max_length=200, unique=True) description = models.TextField() code = models.TextField() It's not convenient to see topics list as a TopicModel object (1) TopicModel object (2) TopicModel object (3) Is there a setup to show fields values (for example 'name') in the list like: TopicModel name1 TopicModel name2 TopicModel name3 I'm sure should be some setup for this in Django, Please notify me if it's possible? -
Django/DRF - minimize DB lookups in foreign keys
Assume the following model realtionships: class Country(Model): name = CharField(max_length=10) class Company(Model): name = CharField(max_length=10) country = ForeignKeyField(to=Country, on_delete=CASCADE) class Department(Model): name = CharField(max_length=10) company = ForeignKeyField(to=Company, on_delete=CASCADE) class User(Model): name = CharField(max_length=10) department = ForeignKeyField(to=Department, on_delete=CASCADE) There is a requirement to show User's country. In DRF I acess the field using following Serializer: class UserSerializer(ModelSerializer): country = CountrySerializer( source='department.company.country' ) class Meta: model = User fields = '__all__' Which leads to an awful lot of database requests (let's take 1000 Users in a list view - for each of them there is a lookup on department->Company->Country -> 3 Lookup queries to database) The requests take quite long for ListViews with many users. My possible solutions so far: Create a country field on the user model that caches the country object. Then create a periodic job that updates the cache (otherwise the first request would take awfully long) -> Downside is higher Complexity, running async jobs, ... Create a country field on the user model that is a database json field that stores the country. Create signal listeners on user, department, company save Method to update the field. -> Leads to great complexity due to signal listeners and spaghetti code … -
How to make celery beat task with django work on all objects rather than just a single object?
I am trying to delete the expired receipts through a scheduler task, but I am facing a problem as each time the function runs, it deletes only 1 object even though there are a lot more. How can I change the code I have to make sure that it deletes all the objects which has passed its expiry date, when the scheduler runs every 60 mins? @periodic_task(run_every=crontab(minute='*/60')) def delete_expired_receipts(): receipts = Receipt.objects.all() for receipt in receipts: if receipt.expiry_date <= timezone.now(): receipt.delete() return "deleted the receipts at {}".format(timezone.now()) return "No receipts" Thanks -
Custom id AutoField in Django model
i want create a custom field with AutoField description: Code generated by the system is increasing gradually, the code consists of 5 digits, there are no 2 identical codes. For example: 00001, 00002 this is my code : class Supplier(models.Model): code = models.AutoField(primary_key=True, max_length=5, blank=False, null=False) name = models.CharField(max_length=200, blank=False, null=False) phone = models.CharField(max_length=11, unique=True, validators=[len_phone]) email = models.EmailField(blank=True, null=True, unique=True) address = models.CharField(max_length=200, blank=False, null=False) -
How to test an api, making use of a django view function
I currently have a Django API mixed with some GRPC stuff. The API makes use of a Django view function @require_GET def django_view_fn(): pass within the api class API: def api_funct(self): result = def django_view_fn return result.pb everything works well as it is right now during normal operation, eg via postman. The only problem I have is, the function doesn't work during Django test/TestCase. It returns a 405 as the response, instead of the expected response from the view function. it only works if I comment out the @require_GET on the view function decorator in the view file -
Django - for each record in database, multiply two values and find the sum
I'm learning Python and Django currently... I have a database with the following fields: ID, amount, number I want to multiply (amount * number) for each record in database, to assign result to variables, and after that to find a sum of all variables. For example: Database: 100 14 50 12 80 10 60 15 . . . etc I want to achieve this: a = 100 * 14 b = 50 * 12 c = 80 * 10 d = 60 * 15 . . .etc and after that, to find a SUM (a+b+c+d....etc), and to display that value in my template. What I have done: VIEWS: def report(request): prof = Test.objects.all() response = TemplateResponse(request,'report.html', {'all': prof}) return response MODELS: class Test(models.Model): number1= models.DecimalField(max_digits=5, decimal_places=2) amount= models.IntegerField() def __str__(self): return self.name @property def profit(self): a = self.amount * self.number1 return a TEMPLATE {% for games in all %} {{ games.profit }} <br> {% endfor %} The code above is displaying the multiplied results for each record in database, but I do not know how to find the SUM of all those new values? Any help will be appriciated. Thanks -
AttributeError at /8/1/ This QueryDict instance is immutable in django rating app
I am using start-rating library in my django application then i am getting this error. Please anyone tell me how to solve it. --------------------------------------------------------- this is my model.py in testapp application in my project class Test(models.Model): name = models.ForeignKey(CustomUser,on_delete=models.CASCADE) subject = models.CharField(max_length=30) ratings = GenericRelation(Rating, related_query_name='test') class TestCreate(LoginRequiredMixin,CreateView): login_url = '/login/' model = Test fields = '__all__' success_url = '/' template_name = 'testapp/test.html' class TestList(ListView): model = Test template_name = 'testapp/test_list.html' class TestDetails(DetailView): model = Test template_name = 'testapp/test_details.html' Here my test_details.html file where i am getting error <ul> <li>{{ object.subject }}</li> {% ratings object %} </ul> please any one tell me solution? please tell me how to solv