Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why we use namspace and tow accounts urls please guide me
hello everyone i have a doubt i am just doing an online Django course in that the tutor sets two accounts in urls.py file can someone please explain me why he had done that and why we use this namespace path('accounts/', include('accounts.urls', namespace='accounts')), path('accounts/', include('django.contrib.auth.urls')) -
How to fix R1710 Either all return statements in a function should return an expression, or none of them should.?
I'm using pylint on my code and getting the error R1710: Either all return statements in a function should return an expression, or none of them should. (inconsistent-return-statements) There are only two possible return statements and they both return expression if I am not mistaken @api_view(["GET", "POST"]) def user_info(request): if request.method == 'GET': username = request.GET.get("username") password = request.GET.get("password") return JsonResponse(error_handle(serialize(username, password))) if request.method == 'POST': username = request.data["username"] password = request.data["password"] return JsonResponse(error_handle(serialize(username, password))) def error_handle(serializer): error = serializer["error"].value if error > 0: return {"success": "false", "internal_code": error} return {"success": "true", "account_token": serializer.data["account_token"], "user_id": serializer.data["id"], "account_name": serializer.data["account_name"], "account_permission": serializer.data["account_permission"], "pin": serializer.data["pin"] } def serialize(user, password): data = Account.objects.get(username=user, password=password) return AccountSerializer(data) -
How to save my crawling data on Django rom?
Im using bs4 for crawling news data. At the first time, I made crawler function on views.py but it make error 504 error due to long loading time. So, I decided to crawling and save data with Django ORM with new python file named 'crawling.py' in the same directory with models. My crawler importing below functions # from django.portal import settings from .models import * import requests from bs4 import BeautifulSoup import urllib.request as req import ssl from bs4.builder import builder_registry import time but it occurs error like below (project) macs-MacBook-Pro:portalpage mac$ python crawling.py Traceback (most recent call last): File "crawling.py", line 2, in <module> from .models import * ImportError: attempted relative import with no known parent package I found way to run my crawler in root directory but I will use crontab for batch jobs so I would like to locate my crawling.py inside app directory. How could I run my crawler on back-end smoothly? -
Django comma-separated field does not work well with admin site
I wrote a custom field as shown below, following the documentation (Django 3.0). This field allows to store a list of comma-separated strings. My problem is that from_db_value is called also when populating the form field in the admin site. For example, suppose that the value in the database is alpha,beta, representing the Python list ['alpha', 'beta']. If I want to change the model instance, the form is populated with the string ['alpha', 'beta']. This would not be terrible, but when I save the model instance (without touching this field), the new value becomes ["['alpha'", " 'beta']"]! In other words, the input to the form field is then interpreted as a comma-separated list. What's the correct way to handle this, in order to have a usable admin site? class CommaSepField(models.CharField): description = "A comma-separated list of strings" def __init__(self, separator=",", *args, **kwargs): self.separator = separator super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() # Only include kwarg if it's not the default if self.separator != ",": kwargs['separator'] = self.separator return name, path, args, kwargs def from_db_value(self, value, expression, connection): print('here', value) if value is None: return value return value.split(self.separator) def to_python(self, value): if value is None: return None … -
is there any solution available app not compatible with buildpack
(pdjangoenv) C:\Users\bhvbh\Desktop\practice django\dental_john>git push heroku master Enumerating objects: 208, done. Counting objects: 100% (208/208), done. Delta compression using up to 4 threads Compressing objects: 100% (201/201), done. Writing objects: 100% (208/208), 2.88 MiB | 47.00 KiB/s, done. Total 208 (delta 26), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://buildpack- registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to dentist-yash. remote: To https://git.heroku.com/dentist-yash.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/dentist-yash.git' I am trying to deploy my app in heroku, but is failing with "App not compatible with buildpack" error. I have added requirement.txt and procfile in my project, yet it is failing. -
How should I solve this weird Primary Key error in Django?
I have a Django to-do list app. In this app there is a page that gives all the details about a task like subtasks and notes, etc. The url of this page is like this "/todo/name of task". I wish to pass the pk of the task as well for security reasons. Also, if I check for a task in the database with its pk along with the title then this would allow a user to have multiple tasks with the same name. But as soon as I pass the pk with the URL, I face weird issues with subtasks and notes. This is my view function that handles the page of the task: def todo_detail(request, title): try: todo = ToDo.objects.get(title=title, creator=request.user) except: return render(request, "ToDo/restrict_access.html") subtasks = SubTask.objects.filter(parent_task=todo) try: note = Notes.objects.get(parent_task=todo) except: note = Notes() if request.method == "POST": note_form = ToDoNotesForm(request.POST) subtask_form = SubTaskForm(request.POST) due_form = DueDateForm(request.POST) if note_form.is_valid(): task_notes = note_form.cleaned_data.get("task_notes") new_note = Notes(content=task_notes) new_note.parent_task = todo new_note.save() todo.has_notes = True todo.save() messages.success(request, "Your notes are saved") return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) elif subtask_form.is_valid(): subtask_title = subtask_form.cleaned_data.get("sub_task") subtask = SubTask(title=subtask_title) subtask.parent_task = todo subtask.parent_task.num_of_subtasks += 1 subtask.parent_task.save() subtask.save() messages.success(request, "Subtask added") return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) elif due_form.is_valid(): days = … -
How to create a website that acts as GUI for a python script
We (my team and I) are developing a prototype sensor that uses a raspberry to preprocess sensor readings. we have a working python script and made a simple GUI using GUIzero to test everything, but this needs a screen to be connected, and that is not possible once the setup is finished and deployed in a field for example. We now have the raspberry acting as a wifi-hotspot, and after connecting to the local network, we can access the RBPi using VNC-viewer, and interact with the simple (guizero-)GUI. This is fine for continuing testing and developing. But once we will distribute the sensor to some test-users, the VNC-solution is not optimal, as it allows too much snooping around on the RBPi. To solve this, we were thinking that a nice solution would be to somehow link our python script with a web page, hosted on the RBPi. A user could then walk upto the sensor, connect to the local wireless network, type in an IP in a browser and the page that loads would then allow starting/stopping the sensor, downloading measured data, managing archiving data, ... Googling points in many directions (Django, flask, ...) and I'm too much of a … -
Nginx, Gunicorn, Django Ubuntu server 502 Bad Gateway
I am getting a 502 bad request error when I try to load a page. I have setup a django app on gunicorn, nginx and supervisor. I have looked at other posts here and they have not fixed the issue. the nginx error logs include messages like this 2020/05/06 15:09:00 [crit] 7361#7361: *4 connect() to unix:/home/USER/APP/APP.sock failed (2: No such file or directory) while connecting to upstream, client: IP, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/USER/APP/APP.sock:/", host: "HOST" supervisor config file [program:APP] command=/home/USER/APP/site/bin/python3.7 /home/USER/APP/site/bin/gunicorn --workers 3 --preload --timeout 120 --bind unix:/home/USER/APP/APP.sock APP.wsgi:application directory=/home/USER/APP autostart=true autorestart=true stderr_logfile=/var/log/APP.err.log stdout_logfile=/var/log/APP.out.log nginx config file server { listen 80; server_name _; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/USER/APP; } location / { include proxy_params; proxy_pass http://unix:/home/USER/APP/APP.sock; } } -
Django dumpdata CommandError: Unable to serialize database: invalid literal for int() with base 10
When I run the following command to export my database in a JSON file : python manage.py dumpdata > datadump.json I have the following error message : CommandError: Unable to serialize database: invalid literal for int() with base 10: b'19 22:00:00' I think that at a moment the command tries to convert a part of a datetime to an integer and fails, but I don't understand why such a thing appears. Any help will be appreciate, thanks -
Unable to run Django application on xampp server (Windows 7)
I am trying to deploy my Django project on xampp server. I have followed the steps from here I am using windows 7, Python 3.6(64 bit), xampp(64 bit) I have also installed mod_wsgi using pip install mod_wsgi command And copied and the mod_wsgi.cp36-win_amd64.pyd file to the apache's modules folder as mod_wsgi.so as mentioned in the steps in the link and added the LoadModule line as well. I have added the following lines to httpd.conf file: <IfModule wsgi_module> WSGIScriptAlias / C:\xampp\htdocs\Hostel\Hostel\wsgi.py WSGIPythonPath C:\xampp\htdocs\Hostel <Directory C:\xampp\htdocs\Hostel> allow from all </Directory> Alias /static/ C:\xampp\htdocs\Hostel\live_static\static_root <Directory C:\xampp\htdocs\Hostel\live_static\static_root> Require all granted </Directory> </IfModule> The apache server is running on port 8012 but when I open localhost:8012 it is unable to load anything. This is my error log: [Wed May 06 19:51:33.663007 2020] [core:warn] [pid 2680:tid 148] AH00098: pid file C:/xampp/apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run? [Wed May 06 19:51:33.697009 2020] [mpm_winnt:notice] [pid 2680:tid 148] AH00455: Apache/2.4.43 (Win64) OpenSSL/1.1.1g mod_wsgi/4.7.1 Python/3.6 PHP/7.2.30 configured -- resuming normal operations [Wed May 06 19:51:33.697009 2020] [mpm_winnt:notice] [pid 2680:tid 148] AH00456: Apache Lounge VC15 Server built: Apr 22 2020 11:11:00 [Wed May 06 19:51:33.697009 2020] [core:notice] [pid 2680:tid 148] AH00094: Command line: 'c:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache' [Wed May … -
What SAML library is better for Django and Python?
I use python 3.6, Django 2.1.5 and SAML 2 I tried many SAML libararies so far. Most of them are either out of date or does not work at all. The last one was: python3-saml-django It produces an error: onelogin.saml2.errors.OneLogin_Saml2_Error: Invalid dict settings: sp_cert_not_found_and_required Any suggestions? -
Uncaught (in promise) TypeError: Request failed with django-pwa
I'm trying to setup django-pwa. I got like this error in console. django-pwa: ServiceWorker registration successful with scope: https://my_domain.com/ Uncaught (in promise) TypeError: Request failed. serviceworker.js:1 Application tab shows this error. No matching service worker detected. You may need to reload the page. What it did Add console.log("console.log('hello sw.js');") in serviceworker.js then console log show the comment, however I got same error at first line of the serviceworker.js I checked to access https://my_domain.com/manifest.json. It was fine. Do you have any idea to solve this problem? Please help me. -
Enable and disable dynamically a field on condition of another one in Django
I created a model TransactionModel and its related ModelForm TransactionForm. As you see below I have a field called 'Type' where I can choose between two values: 'EXPENSE' and 'INCOME'. When I choose either of them I want to be able to disable either the 'expenses' or the 'incomes' field dynamically in the form so that the user does not select both. Below is the Model class TransactionModel(models.Model): type = models.CharField(max_length=100, choices=TransactionType.choices, null=True, default=TransactionType.expense, verbose_name=_('type')) title = models.CharField(max_length=200, verbose_name=_('title')) slug = models.SlugField(max_length=200, unique_for_date='publish') amount = models.DecimalField(max_digits=8, decimal_places=2, verbose_name=_('amount')) created = models.DateTimeField(auto_now_add=True, verbose_name=_('created')) publish = models.DateTimeField(default=timezone.now, verbose_name=_('publish')) updated = models.DateTimeField(auto_now=True, verbose_name=_('updated')) expenses = models.CharField(max_length=200, choices=ExpenseType.choices, blank=True, verbose_name=_('expenses')) incomes = models.CharField(max_length=200, choices=IncomeType.choices, blank=True, verbose_name=_('incomes')) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='katika_transaction') Here is the Form class TransactionForm(BSModalForm): class Meta: model = TransactionModel exclude = [ 'slug', 'user', ] def __init__(self, *args, **kwargs): super(TransactionForm, self).__init__(*args, **kwargs) if self.fields['type'] == 'EXPENSE': self.fields['incomes'].disabled = True self.fields['expenses'].disabled = False else: self.fields['expenses'].disabled = True self.fields['incomes'].disabled = False As you can see I tried to put some if condition in init of the form to do it but it doesn't work at all. in the views I don't know if I have to change something but I will also share … -
Passing anonymous users from one view to another in Django 3.0.5
I'm trying to create a fully anonymous survey, where the survey participant enters a landing site (index.html), clicks a link and is directed to a survey view. On this survey (pre_test.html) page, I want to assign a new Participant object with a primary key and link that to the Survey model via a foreign key. Because this Survey isn't the main part of my study, I want to send that Participant object to a new view, where the Participant primary key is again used as a foreign key to link to another model (call it Task). What I've tried so far in the views.py is: def pre_test(request): if request.method == "POST": participant = Participants() participant.save() participant_pk = participant.pk form = PreTestQuestionnaireForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() post_primary = PreTestQuestionnaire(pk=post.pk) post_primary.Analyst_id = Participants(pk=participant_pk) post_primary.save() request.session['user'] = participant_pk return HttpResponseRedirect(reverse('main:picture_test')) else: form = PreTestQuestionnaireForm() return render(request, 'study/pre_test.html', {'form': form}) def picture_test(request): obj = Participants(Unique_ID=request.session.get('user')) # Unique_ID is the pk I've set for Participants but when calling print(obj) all I get is Participants object (None). What am I missing in using the session? Should I not be using sessions in this way at all, or should I create actual users in another … -
How to provide binary field with Django REST Framework?
Is it possible to provide a backend endpoint where the response is a json containing some field values and a data blob? I have the following model and serializer: class NiceModel(db_models.Model): index = db_models.IntegerField() binary_data = db_models.BinaryField() class NiceSerializer(serializers.ModelSerializer): class Meta: model = models.NiceModel fields = ( "index", "binary_data", ) this serializer produces a json like the following: { "index": 1, "binary_data": "veryveryveryveryveryverylongtext" } Is this very long text a string representation of the binary data handled by DRE? If so, how can I read this data with javascript? Am I doing it the wrong way? should I create an endpoint only for the blob data and forget about the json format? Thanks in advance. -
I just setup python django and Im unable to import
I just finished setup python django I did everything in the video and I wrote the most simple code from django.shortcuts import render from django.http import HttpResponse def hello(request): return HttpResponse("<h1>Hello world!</h1>") I imported it to the url and it works as expected but the issue is I get this:It saying unable to import I dont know why it saying that bc it works well. what is wrong with the program? -
drf - How to filter on 1 item given a many to many relationship
I have 2 tables Product and Price. A product can have multiple prices. This in order to remember the old prices of the product. In my product view I have the following code: products = ProductFilter(filters, queryset=products.all()) ProductFilter is a custom filter class. The filter variable is the same as request.GET. This is what the filter looks like: class ProductFilter(django_filters.FilterSet): ... price__final_price__gte = django_filters.NumberFilter( field_name="price__final_price", lookup_expr="gte" ) price__final_price__lte = django_filters.NumberFilter( field_name="price__final_price", lookup_expr="lte" ) price__currency = django_filters.CharFilter() class Meta: model = Product fields = ["name", "external_id"] This is the problem. If product A has for example 3 prices. Product A: 1. 50$ - 2020/march 2. 20$ - 2019/dec 3. 60$ - 2019/jan When I filter, I would only like to filter on the most recent price. So if my filter had price__final_price__lte: 30 I wouldn't want this product to be selected, because the price on 2019/dec was indeed under 30, but the most current price is not. In what way do I need to change my ProductFilter class to make this possible? (Some ideas I had where to look for the closest date given the current date, but I couldn't get this to work.) Any help would be greatly appreciated. -
Clear Table data on server restart in django
I'm trying to add default data in my table in Django and then create a restful API that changes that data and when I turn the server off and restarts it again the data should be the default one. But it's not working with this code. My Migrations File(0001_initial.py) initial = True dependencies = [ ] def insertData(apps, schema_editor): Login = apps.get_model('restapi', 'Users_Details') user = Login(name="admin", email="abc@gmail.com", password="abcd123456") user.save() operations = [ migrations.CreateModel( name='Users_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('email', models.CharField(max_length=100, unique=True)), ('password', models.CharField(max_length=15, validators=[django.core.validators.RegexValidator('^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.')])), ('confirm_password', models.CharField(max_length=15, validators=[django.core.validators.RegexValidator('^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.')])), ], ), migrations.RunPython(insertData) How can I reset the data to its default(initial) data every time I restart the server. -
Django rest framework csrf exempt when doing ajax post call
I'm trying to pass data via ajax POST request but getting a 403 ERROR. I've tried to use CsrfExemptMixin from braces.views but that doesn't resolve the issue. I'm new to api calls with drf so maybe my methods are incorrect. View class DialogListView(CsrfExemptMixin, viewsets.ModelViewSet): # queryset = Dialog.objects.all() serializer_class = DialogSerializer # http_method_names = ['get', 'delete'] def get_queryset(self): data = self.request.data print('helllo') print(self.request.data) # for k in data: # print(k) try: owner_profile = Profile.objects.get(user=User.objects.get(username=data.get('owner'))) opponent_profile = Profile.objects.get(user=User.objects.get(username=data.get('opponent'))) return Dialog.objects.get(Q(owner=owner_profile, opponent=opponent_profile) | Q(owner=opponent_profile, opponent=owner_profile)) except ObjectDoesNotExist: owner_profile = Profile.objects.get(user=User.objects.get(username=data.get('owner'))) opponent_profile = Profile.objects.get(user=User.objects.get(username=data.get('opponent'))) return Dialog.objects.create(owner=owner_profile, opponent=opponent_profile) -
Image missing in RSS/ATOM with Django
I'm trying to attach an image to my ATOM and RSS syndication feed thanks to the Django's documentation : https://docs.djangoproject.com/fr/1.11/ref/contrib/syndication/ I have to kind of feed : http://example.com/rss and http://mywebsite.com/atom rss.py class LatestEntriesFeed(Feed): title = "MyWebsite" link = "/" description = "Latest news" def items(self): return Articles.objects.filter(published=True).order_by('-date')[:5] def item_description(self, item): return '<![CDATA[ <img src="http://example.com/image.jpeg" /> ]]>' def item_title(self, item): return item.title def item_pubdate(self, item): return item.date def item_updateddate(self, item): return item.update def item_author_name(self, item): return item.author def item_author_link(self, item): item_author_link = Site_URL + reverse('team', kwargs={'username': item.author}) return item_author_link def item_author_email(self): return EMAIL_HOST_USER class LatestEntriesFeedAtom(LatestEntriesFeed): feed_type = Atom1Feed subtitle = LatestEntriesFeed.description So I think I have to use CDATA into the description html tag. However, in Django (version 1.11), item_description doesn't return <description> tag in the XML, but a <summary> tag. Is it fine or is it the source of the issue ? Otherwise, I tried to scan with W3C validator and I get 2 errors (or just warnings ?) 1) Self reference doesn't match document location 2) Invalid HTML: Expected '--' or 'DOCTYPE'. Not found. (5 occurrences) -
RelatedObjectDoesntExist error while trying to get current username through admin model
This is my model: def get_form_path(instance,filename): upload_dir=os.path.join('uploaded',instance.hostname,instance.Class) if not os.path.exists(upload_dir): os.makedirs(upload_dir) return os.path.join(upload_dir,filename) class Book(models.Model): Name= models.CharField(max_length=100) Class= models.CharField(max_length=100) Content =models.FileField(upload_to=get_form_path) hostname=models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,on_delete=models.CASCADE) def __str__(self): return self.Name def delete(self, *args, **kwargs): self.Content.delete() super().delete(*args, **kwargs) This is form.py class BookForm(forms.ModelForm): class Meta: model=Book exclude=('hostname',) fields=('Name','Class','Content') class BookAdmin(admin.ModelAdmin): exclude=('Name','Class','Content',) form=BookForm This is my admin.py: class BookAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'hostname': kwargs['queryset'] = get_user_model().objects.filter(username=request.user.username) return super(BookAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) def get_readonly_fields(self, request, obj=None): if obj is not None: return self.readonly_fields + ('hostname',) return self.readonly_fields def add_view(self, request, form_url="", extra_context=None): data = request.GET.copy() data['hostname'] = request.user request.GET = data return super(NotesAdmin, self).add_view(request, form_url="", extra_context=extra_context) admin.site.register(Book, BookAdmin) Im not getting where I'm going wrong? complete error line is"upload.models.Book.hostnamee.RelatedObjectDoesnotExist:Book has no hostname please guide me through this..Thanks in advance -
How do I input the newline from textarea in HTML and put that to postgresql database through Django?
I am getting an input from the user through an HTML textarea and I need to push that to database. Ex: if user enters -- "hey how are you? \n Its great to have u here." The textarea only takes "hey how are you" and saves only this to the database but I want the whole text instead. Here is the create.html <!doctype html> {% load static%} <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'bootstrap-4.4.1-dist/css/bootstrap-grid.min.css' %}" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'bootstrap-4.4.1-dist/css/bootstrap.min.css' %}" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'styles.css' %}"> </head> <body style="background-color: lightskyblue;"> <nav class="navbar navbar-expand-lg navbar-dark bg-dark mynavbar"> <a class="navbar-brand brand" href="index">notify</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse " id="navbarSupportedContent"> <ul class="navbar-nav"> {% if user.is_authenticated %} <li class="nav-item navlinks"> <a class="nav-link" href="logout">Logout</a> </li> <li class="nav-item navlinks" style="margin-top: 9px;"> <span style="color: azure;">Hello</span><a class="nav-link" href="#" style="display: inline;">{{user.first_name}}</a><span style="color: azure;">!!</span> </li> {% else %} <li class="nav-item navlinks"> <a class="nav-link" data-toggle="modal" data-target="#exampleModalCenter2"><svg class="bi bi-person-fill" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M3 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H3zm5-6a3 … -
i'm working on the project where i need to add the operators in the data but it will gives an error to me
MY VIEWS CODE== def addoperator(request): if request.method=="POST": opera = User.objects.create_user( username=request.POST['name'], email=request.POST['email'], password=request.POST['password'] ) s=Operator() s.user=opera s.phonenumber=request.POST['number'] s.gender=request.POST['gender'] s.address=request.POST['address'] s.picture=request.FILES['userimage'] s.document=request.FILES['document'] s.save() return render(request,'Adminside/addoperators.html') else: return render(request,'Adminside/addoperators.html') MY MODELS CODE==== class Operator(models.Model): # This field is required. user = models.OneToOneField(User,on_delete=models.CASCADE,default='') # These fields are optional gender=models.CharField(max_length=200,default='') phonenumber=models.CharField(max_length=200,blank=True) address=models.CharField(max_length=200,blank=True) picture = models.ImageField(upload_to='operator/', blank=True) document = models.ImageField(upload_to='operator/', blank=True) status=models.CharField(max_length=100,default='PENDING') def isActive(self): if self.status=="ACTIVE": return True else: return False def isDisable(self): if self.status=="DISABLE": return True else: return False So, the main thing is that when i add the operator it will gives an error regarding the operator by saying that there is no user_id column in the operator model. but i only gives the user field in the operator model as you can see in the models code and i don't know how to resolve it. and i will show the error below and please help i'm stuck on this for like two to three days. and important thing for doing this i extended the auth_user tabel to enter the other fields like gender,images and phonenumber etc. MY ERROR FOR ADDING THE OPERATOR OperationalError at /admin/Adminside/operator/ no such column: Adminside_operator.user_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/Adminside/operator/ Django Version: 2.2.4 Exception Type: OperationalError Exception … -
how can i configure apache with django
I want to ingrate apache server with django, but i still have error, can anyone help me plz. i install apache i configure variable environnement for apache i install wsgi i modify wsgi.py because i work with windows i make this code in httpd.conf WSGIScriptAlias / "C:/users/akm/downloads/projet/testoreal/testoreal/testoreal/wsgi_windows.py" WSGIPythonPath "C:/users/akm/downloads/projet/testoreal/testoreal/site-packages"; Order deny,allow Allow from all and i steel can't open the server Thanks -
how can I connect with mongoDB container database from Host
I'm using MongoDB container. and I want to connect to MongoDB from host through django I import "djongo"(module to use django with mongoDB) at settings.py at django. I changed many time the value of host and port but I didn't worked. DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': True, 'NAME': 'mongoTest1', 'HOST': 'mongodb://localhost:17017', 'PORT': 27017, 'USER': 'root', 'PASSWORD': 'password', 'AUTH_SOURCE': 'password', 'AUTH_MECHANISM': 'SCRAM-SHA-1', } } container and I got this errors with python manage.py runserver enter image description here I think there are no problem with ports. Because I just simply bind 17017(host)->27017(mongo container) I only created "root" user at mongoDB and create db, collections to use.