Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error on multiple deploy apache mod_wsgi Django
i'm deploy 2 apps with APACHE and MOD_WSGI the problem is that the app2 get the url of static files from app1 this is my code django.conf: <VirtualHost *:80> WSGIPassAuthorization On WSGIDaemonProcess rgmanagement python-path=/var/www/html/inventariosRG:/home/roo/vproduccion/lib/python2.7/site-packages WSGIScriptAlias /rgmanagement /var/www/html/inventariosRG/inventarios/wsgi.py process-group=rgmanagement WSGIDaemonProcess facturacion python-path=/var/www/html/facturacion:/home/roo/vproduccion/lib/python2.7/site-packages WSGIScriptAlias /facturacion /var/www/html/facturacion/inventarios/wsgi.py process-group=facturacion <Directory /var/wwww/html/inventariosRG/inventarios> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /var/www/html/inventariosRG/static <Directory /var/www/html/inventariosRG/static> Require all granted </Directory> <Directory /var/www/html/facturacion/inventarios> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /var/www/html/facturacion/static <Directory /var/www/html/facturacion/static> Require all granted </Directory> DocumentRoot /var/www/html ErrorLog /var/www/html/error.log CustomLog /var/www/html/access.log combined </VirtualHost> i set differents url for static files on this file, but i don't know why get the incorrect static files, please any suggest thanks..!! I'm using CentOS 7 -
ModuleNotFoundError: No module named 'rest_framework'. How can I fix this error?
I am new to Django. I am using Ubuntu, Apache, and virtualenv. I am running Ubuntu on DigitalOcean. I am trying to use Django and React together. So I downloaded djangorestframework. But when I run the server, I encountered this problem. (new_app) sot232@ubuntu:/var/www/html/django_app/commercial$ python3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/sot232/new_app/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/sot232/new_app/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/sot232/new_app/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "/home/sot232/new_app/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/sot232/new_app/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/sot232/new_app/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/sot232/new_app/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/sot232/new_app/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' I included rest_framework properly in the settings.py file. INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'commercial', ] I tried these commands. sudo pip3 install djangorestframework sudo pip install djangorestframework … -
I'm getting 'NoneType' object has no attribute 'add' and can't get around it
I'm trying to update my database but keep getting the 'NoneType' object has no attribute 'add'error tasksite = "test site" pk = 2 user_object = User.objects.get(pk=pk) user = user_object.username profile_object = UserProfile.objects.get(user=user_object) model_field = profile_object.received_task_site_requests model_field = model_field.add(tasksite) I'm expecting received_task_site_requests on the profile object to change to 'test site' but I'm getting 'NoneType' object has no attribute 'add'error -
Importing None fields in a CSV
I have an historical db table of people in jobs that includes start and end date fields. I am inserting from a csv, and my script worked fine, except Python/Django sees my None fields as 'None', and it refuses to insert the rows that have empty end dates, meaning, all current jobholders are skipped. This except portion of a try/except failed: except ValidationError as v: if row['end_date'] == 'null' or 'None' or '': row['end_date'] = None as did this one: except ValidationError as v: if row['end_date'] in ['null', 'None', '']: row['end_date'] = None I solved the problem by filtering out the current jobholders, and running them in a separate csv with the script modified to: end_date=None However, what I really need is some way to use a variable, like value... if row[value] == 'None': row[value] = None because I have more csv's to run, with other fields besides dates, and some of them are going to have empty/None values, too. Would some kind of string replace work? if row[value] == 'None': row[value].replace(row[value], None) or maybe default=None in the definition of the end_date field on my model? But then how do I make Django see the default value instead of the … -
Receiving the application URL. Django
I need to get the current URL of my application in my views.py. Not the bookmark I am in but the address to the home page (all). I finded this solution: url = "{0}://{1}".format(request.scheme, request.get_host()) But i but I think it can be simpler . Not using 'request ....' twice and by obtaining an interpretation of one variable. Any good suggestions will be appreciated. -
reverse for account_login not found in Django
I'm trying o add to my Django project a registration view from the django-allauth package. I added the view to my urls.py file but i keep getting the following error: Reverse for 'account_login' not found. 'account_login' is not a valid view function or pattern name. Here is how i added the view to my urls: from allauth.account.views import SignupView urlpatterns = [ path("signup/", SignupView.as_view(), name="account_signup"), ] I don't really understand what am i missing when importing the view, can anyone help me? -
Django display Listview in include in template
I have a django project with a home.html in an app called core: {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} {% if user.is_authenticated %} <span>You are now logged in as {{ user.name }}</span> {% include "headlines.html" %} <p><a href="{% url 'logout' %}">logout</a></p> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">login</a> <a href="{% url 'signup' %}">signup</a> {% endif %} {% endblock %} I have a headlines.html in another app that handles my api routes: <html><body> <h1>Headlines</h1> <ul> {% for headline in object_list %} <li>{{ headline.headline }}</li> {% endfor %} </ul> </body></html> At the moment I'm not getting any data from headlines in my home page. I know how to query my model, but I want to simulate an api call from a separate frontend. How do I query the api from a template? -
How to make a field in Serializer both readable and writeable
I am writing a Serializer for my model which will be accessed using GET, POST and PATCH endpoints. I have a property in my model which I am using as a source for a field. However, using source= in serializer field is making it ready-only. If I remove the source="get_field1" from the field1 = serializers.NullBooleanField(source="get_field1") then I am able to update the data. But I HAVE to use the source to get the right value of the field. class MyModel(models.Model): field1 = NullBooleanField(default=None) @property get_field1(self): data = True # ...some logic return data Now I have a serializer that I am using class MyModelSerializer(serializers.ModelSerializer): field1 = serializers.NullBooleanField(source="get_field1") class Meta: model = MyModel fields = ('field1') Now in my API endpoint, I do this serializer = MyModelSerializer(my_model, data=request.data, partial=True) if serializer.is_valid(): serializer.save() # <- throws error "can't set attribute" -
Paypal - when is the most appropriate time to save an order into the database
I have been questioning when is the most appropriate moment to save the order to the database, so everything works the best possible. I created my own shopping cart with Django, working well! In theory I have these options to save the order in the database: 1) before client goes to paypal The client may not finish the payment and I will have an obsolete order in my database 2) when the client is in paypal Ideally I would store the order when the client pays 3) after the client returns from paypal The client may think the payment was already processed, and decides to close the window without returning to the store. I receive the payment, but I can't notify the client with the custom email I implemented option 1) but I'm not completely happy about this, I want to know the opinion someone with experience -
Need help admin user who create other user
I am trying to create a login system with admin user, teacher and student where admin user will create teacher and student account. What are the requirements for this system? -
How to pass an argument to value in forms.BooleanField
I try to pass an argument to value in a form field but in the template it displays this argument as a string of characters and not as a variable. checkbox =forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'class':'checkbox', 'value':'{{ ue.code_ue }}'})) -
Django query : Request with startswith in an array
here is my code : q = [ "78", "95", "77", "91", "92", "93", "94", "75", "27", "28", "45", "89", "10", "51", "02", "60", "27", ] query = reduce(operator.and_, (Q(code_postal__startswith=item) for item in q)) result = Record14.objects.filter(query) for r in result : print(r) I want a query with all the objects from Record14 where the code_postal begin with the values in the q array. I have the data in my database i'am sure, but the query is empty ... I don't understand why. -
Extra field of ModelForm, in InlineModelAdmin
To add an extra field in the admin add page, the following code will work: models.py: class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.PROTECT) forms.py: class ChildForm(forms.ModelForm): extra_field = forms.CharField() class Meta: model = Child fields = '__all__' admin.py: @admin.register(models.Child) class ChildAdmin(admin.ModelAdmin): form = forms.ChildForm How can I add the same extra field when Child is an inline to Parent in the Parent add page? The following admin.py: class ChildInline(admin.TabularInline): model = models.Child form = forms.ChildForm @admin.register(models.Parent) class ParentAdmin(admin.ModelAdmin): inlines = (ChildInline,) results in: Traceback (most recent call last): File "django/db/models/options.py", line 617, in get_field return self.fields_map[field_name] KeyError: 'extra_field' ... django.core.exceptions.FieldDoesNotExist: Child has no field named 'extra_field' ... AttributeError: Unable to lookup 'extra_field' on Child or ChildInline -
How to obtain foreign key field name in post method?
I have an API which I pass some sample data. I am overwriting the post method by copying the Queryset so I can manipulate the output data. I would like to access the value of a foreign key relationship but I can only access the foreign key itself. Like so: def post(self, request, *args, **kwargs): data_request = request.data data_request = data_request.copy() machine_na = data_request.__getitem__('project') ##this gives me the id of the foreign key data_request.__setitem__('project', str('my value')) return Response(data_request, *args, **kwargs) Now that works. But I can't access the name of the foreign key. My models as Foreign Keys: class Machine(models.Model): machine_name = models.CharField(max_length=120, primary_key=True) def __str__(self): return self.machine_name class Project(models.Model): project_name = models.CharField(max_length=120, primary_key=True) def __str__(self): return self.project_name My model that refers to the others: class Simulation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) machine = models.ForeignKey(Machine, on_delete=models.CASCADE, default=1) project I hope I am clear enough. I would like to access the specific name of, for example, foreign key 2. calling 'project.project_name' doesn't work and everything else I tried also not. Any help is highly appreciated. Thanks in advance -
is it possible to change the django things by changing the data of database through pgadmin?
I am confuse about the pgadmin4 interface. I want to update my database using pgadmin4 and change the database things in django without migrating it. is it possible? note: I am currently working in postgres database. -
Problem with custom authentication and login in Django
I'm getting a problem with my custom authentication backend with django. For a school project I need to authenticate with GitHub so I used a package named "PyGithub". I created my custom backend but I got the error "Cannot force an update in save() with no primary key." when i'm calling login() method. I don't really know what to do except overriding the login method but don't know how to do this. Here's my custom authenticate function from my custom backend : def authenticate(self, request, username=None, password=None): try: g = Github(username, password) gitUser = g.get_user() user = User(username=username) return user except UnknownObjectException : return None return None And here's my function which calls authenticate() and login() : def connexion(request): error = False if request.method == "POST": form = ConnexionForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) if user: login(request, user) else: error = True else: form = ConnexionForm() return render(request, 'connexion.html', locals()) Thanks by advance ! -
How to migrate models in Django based on PGsql
I'm following all of the tutorials and references I can reach. However, none of them works. The only thing I want to do is super simple. I just want to add one column to my built model. In this situation, I want to add One ForeignKey to Card. I changed the model then I makemigrations then I migrate. But Django always tell me no migrations apply. Why? I try to delete all the migration files and migrate again. The same thing happens. Here are some model files. ... class Card(models.Model): add_time = models.DateTimeField(auto_now_add=True) cata = models.CharField(max_length=150,default='夹芯板') test_cata = models.ForeignKey(Example,on_delete=models.PROTECT,null=True) price = models.CharField(max_length=10,default='1') noise = models.CharField(max_length=10,default='1') flame = models.CharField(max_length=10,default='1') moisture = models.CharField(max_length=10,default='1') compressive = models.CharField(max_length=10,default='1') corrosion = models.CharField(max_length=10,default='1') shock = models.CharField(max_length=10,default='1') thermal = models.CharField(max_length=10,default='1') eng_name = models.CharField(max_length=50,default='1') name = models.CharField(max_length=100,default='1') card = models.BooleanField(default=True) door = models.BooleanField(default=False) descrip = models.CharField(max_length=1000,default="",blank=True) upload = models.FileField() def __str__(self): return self.name class Example(models.Model): filename = models.CharField(max_length=150) cata = models.CharField(max_length=150) description = models.CharField(max_length=500) add_time = models.DateTimeField(auto_now_add=True) # image = models.ImageField(max_length=100, upload_to=our_upload_to, default='ourwork/default/default.png', verbose_name='图片') # upload = models.FileField() def __str__(self): return self.filename ... Here is the command I ran in console. python .\manage.py makemigrations ourwork Then I got: Migrations for 'ourwork': ourwork\migrations\0001_initial.py - Create model Card - Create … -
Creating fixture from json file in django
I'm having problems loading my fixture in Django 2.2 I have a file called data.json in my fixtures folder like this: [{"model": "Headline", "pk": 1, "fields": {"article_link": "https://www.huffingtonpost.com/entry/versace-black-code_us_5861fbefe4b0de3a08f600d5", "headline": "former versace store clerk sues over secret 'black code' for minority shoppers", "is_sarcastic": 0}}, {"model": "Headline", "pk": 2, "fields": {"article_link": "https://www.huffingtonpost.com/entry/roseanne-revival-review_us_5ab3a497e4b054d118e04365", "headline": "the 'roseanne' revival catches up to our thorny political mood, for better and worse", "is_sarcastic": 0}}, {"model": "Headline", "pk": 3, "fields": {"article_link": "https://local.theonion.com/mom-starting-to-fear-son-s-web-series-closest-thing-she-1819576697", "headline": "mom starting to fear son's web series closest thing she will have to grandchild", "is_sarcastic": 1}}] I have this model: from django.db import models class Headline(models.Model): article_link = models.CharField(max_length=250) headline = models.CharField(max_length=500) is_sarcastic = models.IntegerField() I keep getting this error and not sure what is wrong? django.core.serializers.base.DeserializationError: -
django: save one field of a formset at a time
My django app connects to a sql server database. On my template I have an editable datatable/formset. Whenever a user edits a field and hits enter, I want only the edited field to be saved. As far as I know AJAX is the only approach to do this, especially if you want the value of the edited field to be the only one transfered to the server. Let's put this case aside for now and accept transferring all data of the formset at once. What would be best practice to identify the chaged field and save only this one? Let's say my formset is based on the model costsperdiem and 'costs' is the name of the editable field then my approach is as follows: check if the formset is valid loop through the forms of the formset using changed_data to seek for the modified field using a model instance to filter for the modified record pass the modified value to the model save the model which looks like this in code: formset = FormSet_CostsPerDiem(request.POST) if formset.is_valid(): for f in formset.forms: if 'costs' in f.changed_data: val2save=f.cleaned_data['costs'] rec2save=costsperdiem.objects.filter(id_costsperdiem=f.cleaned_data['id_costsperdiem']) rec2save.costs=val2save rec2save.save() What is best practice to do something like this? -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method'
I am trying to do an API call between Django and Python But I am getting error. My logic is to get the Employee data by ID. If the user gives the ID the record related to that particular id will be shown if user doesn't pass ID all the records will be shown to user. And if the id is not present it will throw a message like user is not available My models.py is class Employee(models.Model): eno=models.IntegerField() ename=models.CharField(max_length=70) esal=models.FloatField() eaddr=models.CharField(max_length=100) My views.py. I have taken one class within that I took 2 functions one to get object by id and other to get all objects class EmployeeCRUDCBV(View): def get_object_by_id(self,request,*args,**kwargs): try: emp=Employee.objects.get(id=id) except Employee.DoesNotExist: emp=None return emp def get(self,request,*args,**kwargs): data=request.body valid_json=is_json(data) if not valid_json: json_data=json.dumps({'message':'This is not a valid json data'}) return self.render_to_http_response(json_data,status=404) pdata=json.loads(data) id=pdata.get('id',None) if id is not None: emp=self.get_object_by_id(id) if emp is None: json_data = json.dumps({'msg': 'The requested resource is not available with matched ID'}) return HttpResponse(json_data , content_type='application/json' , status=404) json_data = self.serialize([emp,]) return self.render_to_http_response(json_data) qs = Employee.objects.all() json_data=self.serialize(qs) return self.render_to_http_response(json_data) I have also taken one separate Mixins.py for serialization and one function for Httpresponse with by default status code 200 from django.core.serializers import serialize import … -
PDF File not getting context data it shows empty table value
This is my college project, i created web app, that app generates some values and Diagrams result now i want to download that result in pdf format, i trying below code but that code create pdf but showing empty table values not showing diagrams. the context data is not getting. i tried below code. please give me suggestion.thank you in advanced. def upload1(request): form = ReadFileForm() if request.method == 'POST': form = ReadFileForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] ascii_data = np.loadtxt(file) data_m_sec = ascii_data data = {} data["RR"] = np.array(data_m_sec) data["BeatTime"] = np.cumsum(data["RR"]) / 1000.0 data["niHR"] = 60.0 / (data["RR"] / 1000.0) info = {} info["beats"] = "{0:.2f}".format((len(data["BeatTime"]))) info["minhr"] = "{0:.2f}".format(min(data["niHR"])) info["maxhr"] = "{0:.2f}".format(max(data["niHR"])) info["meanhr"] = "{0:.2f} bps".format(np.mean(data["niHR"])) info["meanrr"] = "{0:.2f} msec.".format(np.mean(data["RR"])) # for RR Histogram fig1 = plt.figure(1) axes = fig1.add_subplot(1, 1, 1) axes.hist(data["RR"], 30, density=1, facecolor="red") axes.set_xlabel("RR (msec.)") axes.set_ylabel("Probability") axes.set_title("RR histogram") axes.grid(True) img_in_memory = BytesIO() plt.savefig(img_in_memory, format="png") img_in_memory.seek(0) image1 = base64.b64encode(img_in_memory.getvalue()) image1 = image1.decode('utf8') plt.close(fig1) context = { "image1": image1, "beats": info["beats"], "meanhr": info["meanhr"], "meanrr": info["meanrr"], "minhr": info["minhr"], "maxhr": info["maxhr"], } return render(request, "upload/base.html", context) return render(request, "upload/upload.html", {"form": form}) def generate_pdf(request): report = upload1(request) template_path = 'upload/base.html' response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="Report.pdf"' html = … -
related items in loop creates many duplicate queries
Rendering a page gets really slow when related objects are requested in a template. class Item(models.Model): name = models.CharField(max_length=160) ... class Box(models.Model): ... items = models.ForeignKey(Item, on_delete=models.CASCADE, null=True) #template {% for item in items %} {{ item.box_set.first }} {{ item.box_set.latest }} {% endfor %} Debug toolbar shows there many duplicate queries. Why is this happening? Is there a way to speed this up? -
Query (get) upper bound of RangeField in django
I want to get the upper bound of a RangeField via django queryset. When you have access to the python object, my_model.size_range.upper works. Not inside the query engine, not working with F, When, Case... class MyModel(models.Model): size_range = IntergerRangeField() MyModel.objects.all().annotate(new_upper=F('size_range__upper') + 1) FieldError: Unsupported lookup 'upper' for IntegerRangeField or join on the field not permitted. Any idea ? -
Object saves to Redis but not database
When I use Model.save() in a task, I see results in the Celery worker (presumably from Redis storage) but it does not hit the (MySQL) database. Furthermore, the objects in Redis have different pks from the ones in the database. Project structure: proj/ proj/ settings/ base.py specific_settings.py myapp1/ celery.py myapp2/ tasks.py views.py manage.py settings.py: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_TASK_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT = ['json'] specific_settings.py imports base.py and is what I actually use, but it does not override these. celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings.specific_settings') app = Celery('myapp1') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() myapp2/tasks.py: from __future__ import absolute_import, unicode_literals from celery import shared_task from .models import MyModel @shared_task def change_project_name(name): print("received task with name `{}`".format(name)) print("before making changes: {}".format(MyModel.objects.values_list('pk', 'name'))) try: project = MyModel.objects.get(pk=1) except MyModel.DoesNotExist: print("did not find project 1") print(MyModel.objects.values_list('pk', 'name')) else: print("found project 1") project.name … -
Python manage.py runserver error doing Python Crash Course
Trying the python crash course web app project. Python manage.py runserver is throwing off a bunch of errors I figured it out actually, but not sure why or how it works, but decided to leave it here in case someone comes across the same problem in the future. In the urls.py file, the textbook tells you to add "url(r'', include('learning_logs.urls', namespace='learning_logs'))," what fixes it is adding this instead of the above, "path('', include('learning_logs.urls'), name='learning_logs')," '''python python manage.py runserver '''