Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'XXXXX' object has no attribute 'request'
I have modified_by in my model. I want someone update that it takes his user instance .I have written in model def save(self,*args,*kwargs): self.modified_by=self.request.user it gives me error above but i have written same in delete method it works.Any suggestion? -
Different language settings for website and API
I have an application with two languages, Farsi and English. This application provides a website which uses Django templates and a simple API with two endpoints using pure Django. Now I'm facing an issue I can't solve: I want the website to load in Farsi by default and the API to load in English. I have set the LANGUAGE_CODE to 'en' so everything loads in English by default. I'm not using session or cookies. Is there anyway I can tell the website to change the language to Farsi while keeping the API in English? Will I have to use cookies for this (I can't go about implementing sessions)? If so will it also affect the API? I have read the Django docs multiple times and still can't figure out the right way to go about this. Any help would be much appreciated. -
DATA_UPLOAD_MAX_MEMORY_SIZE is overriden with django 2.2.6
I was using django 1.11.23 until last month and there was no DATA_UPLOAD_MAX_MEMORY_SIZE mentioned in my settings.py. It used to allow payloads of sizes far greater than the default value of 2.5MB. However, on switching to Django 2.2.6 and (djangorestframework upgraded from 3.9.1 to 3.10.3) it has suddenly started raising the "RequestDataTooBig" Exception. Now to run the same payloads, I am forced to add DATA_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024 *100 (after seeing multiple answers here). I also switched from python 2.7 to python 3.6.8 but that ideally should not be causing any issue. -
Id field set to auth value in Django
I have a custom id field in my model that looks like this: id = models.CharField(primary_key=True, max_length=400) In my view, I render the form with the auth_id that the user signs in with in the context and then set the value of the id field in the html. See below. in my view: if request.method == 'POST': form = PersonalDetailsModelForm(request.POST) if form.is_valid(): form.save() inject(form, userdata, Section.personalDetails) return HttpResponseRedirect('/IntakeForm/2' + '?instance=' + str(form.instance.id)) else: return HttpResponse(form.errors) # else: # return render(request, 'LSPIntake/personal_details_section.html', {'soldier': form, 'auth_id':userdata['user_id']}, # {'auth0User': auth0user, 'userdata': json.dumps(userdata, indent=4)}) else: form = PersonalDetailsModelForm(label_suffix="") # get rid of default colon after labels context = {'soldier': form, 'auth_id':userdata['user_id']} # try: return render(request, 'LSPIntake/personal_details_section.html', context, { 'auth0User': auth0user, 'userdata': json.dumps(userdata, indent=4)}) in the html file: <input type="hidden" name="id" id="id_id" value={{auth_id}}> Now, whenever I sign in again to the same user, django says that the form is not valid. I think it's because it won't allow the same value to be entered into "id" twice since it is a primary_key. I want that to happen, however because if the same user signs in to their account, I don't want there to be multiple records - I want it to update an existing record. … -
BeautifulSoup won't replace string
Function doesn't throw any error but strings stay the same after execute. It look like replace_with is doing nothing. So I checked types of var's and I thing this is the problem: <class 'str'> <class 'bs4.element.Tag'> fixed_text is str and blog_text is tag type. I don't know how to resolve this problem. def replace_urls(self): find_string_1 = '/blog/' find_string_2 = '/contakt/' replace_string_1 = 'blog.html' replace_string_2 = 'contact.html' exclude_dirs = ['media', 'static'] for (root_path, dirs, files) in os.walk(f'{settings.BASE_DIR}/static/'): dirs[:] = [d for d in dirs if d not in exclude_dirs] for file in files: get_file = os.path.join(root_path, file) f = open(get_file, mode='r', encoding='utf-8') soup = BeautifulSoup(f, "lxml", from_encoding="utf-8") blog_text = soup.find('a', attrs={'href':find_string_1}) contact_text = soup.find('a', attrs={'href':find_string_2}) fixed_text = str(blog_text).replace(find_string_1, replace_string_1) fixed_text_2 = str(contact_text).replace(find_string_2, replace_string_2) blog_text.replace_with(fixed_text) contact_text.replace_with(fixed_text_2) -
Django and AJAX: Is it possible, or good practice, to submit a single form from a formset using AJAX?
My django application displays forms in formsets which are filled in by the user. These can be up to 10 forms. I have tried to work out a way to 'save' the data from a single form in this formset as this can take a long time, and users may be interrupted and not submit the entire formset, losing their work. Is this possible (or is it very bad practice?) I am thinking something along the lines of: forms.py: class ResultsForm(forms.ModelForm): result = forms.CharField( widget=forms.Textarea(attrs={'rows': 4}), required=False, label='Result') class Meta: model = Result fields = ( 'id', 'result', ) views: def save_result(request): if request.method == 'POST' and request.is_ajax(): form = ResultsForm(request.POST) if form.is_valid(): form.save() templates: {% for form in formset %} <tr> {{form.id}} <td>{{form.evidence}}</td> <td> <button id='{{ form.prefix }}-save-button' action="{% url 'results:save_result' %}" type='button' class="btn btn-info btn-sm save-result">Save</button> </td> </tr> {% endfor %} Will this work without the correct formset management? Can i isolate a form and validate it/save it using the proper django validation method? -
Heruko Time OUT
I created a django app which works perfectly fine in localhost. The SQL server is in GoogleCloud SQL. There is a simple student form registration, for which I create a form using forms.ModelForm. I use logger to find if it passed/failed the is_valid() constraint. Something like, if form.is_valid(): logging.info("passed") student = form.save() logging.info("Saved) else: logging.error("Failed") When I try with local host, it works fine in getting the POST data and creating objects in the Cloud server, but using heruko, it gets timed out. It does retrieve the POST data but times out even during checking the form, and not even print the log line of passed, giving out a timeout, but it shouldn't be a trouble regarding the SQL server because it didn't log the line in the first place to move to next step, and SQL connectivity works fine in localhost too in creating objects and posting. It throws 503 in at=error code=H12 desc="Request timeout" method=POST path="/student/register/" host=x-y.herokuapp.com request_id=----f43d65a33f03 fwd="98.210.122.173" dyno=web.1 connect=0ms service=30001ms status=503 bytes=0 protocol=https -
How to create a unique id for an entire django formset?
I have created a formset to submit project costs and i want each submission to have a unique id. I want to use the submission id in a url later on(ie "projects/1/cost-submission-edit/3"). 1 is the project's id and 3 should be the cost submission id. The formset is defined as: models.py class ProjectData(models.Model): project_name = models.CharField(max_digits = 20) client = models.CharField(max_digits= 15) class ProjectCostSubmission(models.Model): project_name = models.ForeignKey(ProjectData, max_digits = 20) cost_name = models.CharField(max_digits= 15) amount = models.DecimalField(max_digits=9) submission_date = models.DateField(auto_now_add=True) payment_approval_date = models.DateField(auto_add_now=True) forms.py class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.label_suffix = "" class Meta: model = ProjectData fields = "__all__" MyFormSet = inlineformset_factory(ProjectData,ProjectCostSubmission, form=MyForm,extra=2) views.py class ProjectCostView(CreateView): template_name = "/project_cost.html" model = ProjectCostSubmission fields = '__all__' form_class = MyForm urls.py path("/projects/<int:project_id>/cost-submission-edit/",ProjectCostView.as_view(),name="costView") After 3 submissions,the edit page renders the formset like this: Project Name Client Cost Name Amount Submission Date Approval Date ------------ ------ -------- ------ --------------- ------------- Project1 Client1 Cost A 1000.00 12/02/2019 12/03/2019 Project1 Client1 Cost B 1000.00 12/02/2019 12/03/2019 Project1 Client1 Cost C 1000.00 12/03/2019 12/03/2019 Project1 Client1 Cost A 1000.00 12/03/2019 12/03/2019 Project1 Client1 Cost F 1000.00 12/04/2019 12/04/2019 Project1 Client1 Cost G 1000.00 12/04/2019 12/04/2019 ------------------------------------------------------------------------- Total: $6000.00 ------------------------------------------------------------------------- with the url "/projects/1/cost-submission-edit/".'/1/' … -
Redis php session handling and fetching saved session on Django
I have saved php session in redis using php session handler and i want to read that session value in Django. The issue is I am getting a byte sting on Django side which seems to be incorrect format for me as I want the value direct by just passing the key to redis server. I want "This is shahiq" only as a result ? -
Is there a way to avoid Gatsby from breaking when a GraphQL node is empty from a Django Rest Framework source?
I am trying to make a simple blog using Gatsby and Django REST Framework for my endpoints. Along with returning the title and content, I am also returning a tags field which could be an array of object and an empty array when the post contains no tags. The error comes up when I try querying a post with no tags (i.e having an empty array). Gatsby breaks since GraphQL cant go forward into querying the children nodes. This is my GraphQL query from my Gatsby page: query MyQuery { allRestApiPosts { edges { node { tags { id tag { color name } } id content title author { profile { first_name last_name profile_photo } } } } } } And the page breaks with this error: There was an error in your GraphQL query: - Unknown field 'tags' on type 'RestApiPosts!'. How can I avoid this error when there are no tags attached to a post? -
Django: inner function with request as parameter
In my views.py, I have the following Function Based View: # Create your views here. @login_required def initial_load(request): # only superusers can upload documents if request.user.is_superuser: if request.method == 'POST': # get the excel sheet excel_file = request.FILES["ExcelFile"] # perform validations validate_uploaded_excel(request, excel_file) # upload file to Document print("still executing") form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('pages:home') return redirect('pages:home') form = DocumentForm() return render(request, 'excel/initial_load.html', {'form': form}) else: messages.warning(request, "You are not a superuser") return redirect("pages:home") as you can observe, I have the function validate_uploaded_excel which has the following code: def validate_uploaded_excel(request, excel_file): message_list = [] # retrieve the sheet names allowed _list = settings.EXCEL_ALLOWED_SHEET_LIST_INDICATORS # check if the sheets names is the one expected (validated, message_sheets) = excel_utils\ .validate_excel_sheet_names(excel_file, _list) message_list.append(message_sheets) # If no errors detected if validated: messages.success(request, "File format is correct") return redirect('pages:home') else: for mess in message_list: # When there was no error, message was set to none if mess is not None: messages.warning(request, mess) return redirect('excel:initial_load') I though that the redirect from validate_uploaded_excel would just redirect to the page, but it seems that Django uploads the file no matter the output of validate_uploaded_excel. How is this possible? How can I avoid such behavior? -
Django Rest Framework - how to save data based on foreign key
I'm working on an app where a user uploads a file. The user chooses a "Project" to assign the file to. Each project is assigned a "user" and an "editor". When the file is uploaded, I'm trying to set the owner of the file based on the "user" from the "project". Project Model: class Project(models.Model): projectCode = models.CharField(max_length=10) projectName = models.CharField(max_length=100) user = models.ForeignKey( User, related_name="projects", on_delete=models.CASCADE, null=True) editor = models.ForeignKey( User, on_delete=models.CASCADE, null=True) creationDate = models.DateTimeField(auto_now_add=True) completedDate = models.DateTimeField(null=True, blank=True) dueDate = models.DateTimeField(null=True, blank=True) def __str__(self): return f"{self.projectName}" Model for the file being uploaded: class Completed(models.Model): completed = models.BooleanField(default=False) url = models.CharField(max_length=100) handle = models.CharField(max_length=30) filename = models.CharField(max_length=100) size = models.IntegerField() source = models.CharField(max_length=50) uploadId = models.CharField(max_length=50) originalPath = models.CharField(max_length=50) owner = models.ForeignKey( User, related_name="completed", on_delete=models.CASCADE, null=True) project = models.ForeignKey( Project, related_name="projectId", on_delete=models.SET_DEFAULT, default=1) uploadDate = models.DateTimeField(auto_now_add=True) editor = models.ForeignKey( User, related_name="editor", on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.filename}" Project Serializer: class ProjectSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Project fields = '__all__' Serializer for file uploaded: class CompletedSerializer(serializers.ModelSerializer): project = ProjectSerializer(read_only=True) owner = UserSerializer(read_only=True) editor = UserSerializer(read_only=True) class Meta: model = Completed fields = '__all__' And finally, the viewset for the uploaded file: class CompletedViewSet(viewsets.ModelViewSet): permission_classes = [ … -
How can I extract cookies of browser(or a particular site) using python or django?I am trying with the following code
import browser_cookie3 import requests import re cj=browser_cookie3.chrome() r=requests.get('https://www.youtube.com/', cookies=cj) get_title = lambda html: re.findall(('(.*?)'), html, flags=re.DOTALL)[0].strip() get_title(r.content) And i am getting the following error- TypeError: cannot use a string pattern on a bytes-like object (It get in line 6.) -
How to edit django DRF API code that queries DB and returns data, to read in a file and upload data
I know there are a lot of questions like this out there, I'm just really confused about my specific case. I have a employee_models.py file with three classes; one with employee names and one with dept details, and then one that combines these two and some other info: from django.db import models class employee_name(models.Model): id=models.AutoField(primary_key=True) first_name = models.CharField(max_length=100, blank=True, null=True) surname = models.CharField(max_length=100, blank=True, null=True) middle_initial = models.CharField(max_length=100, blank=True, null=True) class employee_dept(models.Model): id = models.AutoField(primary_key=True) employee = models.ForeignKey('employee_name',blank=True, null=True) dept_name = models.CharField(max_length=100, blank=True, null=True) time_in_dept = models.CharField(max_length=100, blank=True, null=True) due_review = models.CharField(max_length=100, blank=True, null=True) class full_employee_record(models.Model): id = models.AutoField(primary_key=True) name = models.ForeignKey('employee_name',blank=True, null=True) dept = models.ForeignKey('employee_dept',blank=True, null=True) address = models.CharField(max_length=100, blank=True, null=True) benefits = models.CharField(max_length=100, blank=True, null=True) I have a serializers.py file: from rest_framework import serializers from employee_models import employee_name,employee_dept class EmployeeNameSerializer(serializers.ModelSerializer): class Meta: model = employee_name fields = "__all__" class EmployeeDeptSerializer(serializers.ModelSerializer): class Meta: model = employee_dept fields = "__all__" class FullEmployeeRecordSerializer(serializers.ModelSerializer): class Meta: model = full_employee_record fields = "__all__" and a Views.py file: class EmployeeNameViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list` and `detail` actions. """ queryset = employee_name.objects.all() serializer_class = EmployeeNameSerializer permission_classes = (permissions.IsAuthenticated, CuratedDataPermission) pagination_class = LongPagination class EmployeeDeptViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list` and `detail` actions. … -
How should I write my Models in django(This case is a little specific)?
I am in a bit of a weird situation right now and hence this question. Say I have a game and I have a website that shows stats for all its players. Now my problem is that I have a bunch of levels and I want to show stats like personal best(least no of moves or time) and stuff for each level to each player on my website. Now if I have to store all this data for each player, how would I do so? Originally I thought why not a table each for a player which has columns of level no, personal best and so on. But, then I would have a 100 tables (or models in this case of django) if I had 100 players and querying for a leaderboard and stuff becomes a problem. So my next best solution I thought was maybe have a table (model) with player names and have as many columns as there are levels and values for each entry would be their personal bests. But, then if I added more levels, scalability becomes an issue and it isn't an elegant solution either. So this is my problem, it isn't very technically to … -
ImportError: cannot import name 'six' from 'django.utils'
Currently, I have upgraded version of Django 2.0.6 to 3.0 and suddenly after calling python manage.py shell command got this error: ImportError: cannot import name 'six' from 'django.utils' (/path-to-project/project/venv/lib/python3.7/site-packages/django/utils/init.py) Full trace: Traceback (most recent call last): File "manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/path-to-project/project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/path-to-project/project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/path-to-project/project/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/path-to-project/project/venv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/path-to-project/project/venv/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/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 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/path-to-project/project/venv/lib/python3.7/site-packages/corsheaders/__init__.py", line 1, in <module> from .checks import check_settings # noqa: F401 File "/path-to-project/project/venv/lib/python3.7/site-packages/corsheaders/checks.py", line 7, in <module> from django.utils import six Similar Questions: I read this Question and django-3.0, release note , but those answers couldn't help me. -
Printing all records with all the attributes
I am from PHP background and very new to Django. I just want to see all the records with it's values for that I have write below code Model file : class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text View file: q = Question.objects.all() print(q) In console it only outputs question_text. How can I print all the records with all the attributes. -
ModuleNotFoundError: No module named 'Social'
Upgrading Django project to Python 3, python3 manage.py check is throwing this traceback. The project works fine in Python 2.7. I cannot figure out what is missing in my pip3 installs. Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "~/src/languages/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "~/src/languages/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "~/src/languages/env/lib/python3.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "~/src/languages/env/lib/python3.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "~/src/languages/env/lib/python3.7/site-packages/django/apps/config.py", line 112, in create mod = import_module(mod_path) File "~/src/languages/env/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 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "~/src/languages/env/lib/python3.7/site-packages/social/__init__.py", line 12, in <module> from Social import _metadata … -
Django Channels: How to keep socket alive
I am trying to use django channels and templates to implement authentication. I know that there is an authentication section in the official website, but I have a question about the socket, which is created in the client side via templates. From my understanding, django templates multi-page application, so if I create a socket in login.html, the socket will be disconnected in main.html, and I have seen it happen. Is there a way to keep the socket alive even if I navigate to different pages? -
social auth with drf and react
I am using rest_framework_social_auth2 library for social authentication and using simple-jwt for authentication urls.py: path('auth/', include('rest_framework_social_oauth2.urls')), settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'image', 'crispy_forms', 'django_countries', 'users', 'corsheaders', 'api', 'sorl.thumbnail', 'rest_framework', 'social_django', 'rest_social_auth', 'django_filters', 'oauth2_provider', 'rest_framework_social_oauth2', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':[ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework_social_oauth2.authentication.SocialAuthentication', ], AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'rest_framework_social_oauth2.backends.DjangoOAuth2', 'django.contrib.auth.backends.ModelBackend',) SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email' } SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] also changed the middleware templates created new application from django backend: this is the postman output: but how can i create api endpoint for facebook, google. -
How to use py dictionary to get names respect to ids in table?
I have id of selected department from dropdown in my database , i want to bind name of that id to table , so it is possible using py dictionary .. how? html <tbody id="myTable"> {% for employee in employees %} <tr> <td>{{ employee.employee_id}}</td> <td>{{ employee.Name}}</td> <td>{{ employee.designation}}</td> <td>{{ employee.department_id}}</td> <td>{{ employee.manager_id}}</td> <td>{{ employee.location_id}}</td> <td> <a href="#editEmployeeModal" class="edit" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a> <a href="#deleteEmployeeModal" class="delete" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i></a> </td> </tr> {% endfor %} </tbody> Here "{{ employee.department_id}}" is binding my id from database , so how can i set id and names in dictionary so i will get name of that id? -
Moving from backend to Django graph
i am quite new in Django and now matplotlib. I want the following code to conert to graph and seek for any help: import numpy as np import pandas as pd from pandas_datareader import data as wb from yahoofinancials import YahooFinancials symbols='AAPL' yahoo_financials = YahooFinancials(symbols) new_data = pd.DataFrame() for s in symbols : new_data[s] = wb.DataReader(s, data_source ='yahoo', start = '2014-1-1')['Adj Close'] a = new_data[s] a contains stock prices and i want them to be in graph. I did with matplotlib in backend in python, but confused how to convert it in graph in Django. Would be thankful to any help and tips. -
Problem while using mypy with my django project
I have implemented mypy in my django rest framework but I am getting errors ModuleNotFoundError: No module named 'config' while running mypy.Is there any wrong with my django_settings_module in my mypy.ini file ? I used to run my project with the command python manage.py runserver --settings=config.settings.development which was working fine but while configuring this setting in the mypy it is giving me error. What I might be doing wrong ? Any help would be appreciated. mypy.ini [mypy] plugins = mypy_django_plugin.main, mypy_drf_plugin.main ignore_missing_imports = True warn_unused_ignores = True strict_optional = True check_untyped_defs = True follow_imports = silent show_column_numbers = True [mypy.plugins.django-stubs] django_settings_module = config.settings.development settings directory /project /config __init__.py urls.py wsgi.py /settings __init__.py base.py development.py wsgi.py app_path = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir) ) sys.path.append(os.path.join(app_path, "project")) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') application = get_wsgi_application() -
RelatedObjectDoesNotExist at /admin/login/
Django beginner. the project is aboud a really basic food delivery app. I have extended the User Model using a One-to-One link as specified here, in order to include a 'city' field when a new user tries to register. The problem is that when I create a superuser in the python shell, and try to access that account from http://127.0.0.1:8000/admin/login/?next=/admin/ and hit login, the following page is returned: As far as I can tell, this is due to the fact that every User/Superuser has to be linked to one Customer object. How can I avoid this? Could a solution be to overwrite the superuser class by specifying that that field 'city' is not needed? If yes, how can I do that? If not, what is the best practice in this case? here is accounts/model.py from django.db import models from django.contrib.auth.models import User from city.models import City from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.ForeignKey(City, on_delete=models.CASCADE) @receiver(post_save, sender=User) def create_customer_user(sender, instance, created, **kwargs): if created: Customer.objects.create(user=instance) @receiver(post_save, sender=User) def save_customer_user(sender, instance, **kwargs): instance.customer.save() If you need any other code to be uploaded, please let me know that, … -
Django with asgi_rabbit why do i get connection closed error. Not establishing new connection
I am using Django with asgi and a rabbitmq broker. It works fine but on some request i get the following error message. And then django loses its connection and does not open a new one. I have no clue where to start searching. I tried with asgi-rabbitmq 0.5.5 but there the same happend always after 60s since rabbitmq did get a heartbeat timeout. But i don't know how to avoid that. dependencies: Rabbit mq 3.8.1 amqp==2.5.2 # via kombu asgi-rabbitmq==0.5.3 asgiref==1.1.2 # via asgi-rabbitmq, channels, daphne autobahn==19.11.1 # via daphne billiard==3.6.1.0 # via celery cached-property==1.5.1 # via asgi-rabbitmq, zeep celery==4.3.0 daphne==1.4.2 # via channels defusedxml==0.6.0 # via zeep django==1.11.26 djangorestframework==3.9.4 kombu==4.6.6 # via celery lxml==4.4.2 # via zeep markupsafe==1.1.1 more-itertools==5.0.0 # via zipp msgpack-python==0.5.6 # via asgi-rabbitmq six==1.13.0 # via asgiref, singledispatch, structlog, txaio, zeep twisted==19.10.0 # via daphne Channels confg: BROKER_URL = 'amqp://' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgi_rabbitmq.RabbitmqChannelLayer', 'CONFIG': { 'url': 'amqp://guest:guest@localhost:5672/%2F', }, 'ROUTING': 'timeline_prototype.apps.core.routing.channel_routing', } } django error (ie. runserver) ERROR daphne.http_protocol http_protocol.py 184 process 2019-12-05 09:31:03 [error ] Traceback (most recent call last): File "/myproject-env/lib/python2.7/site-packages/daphne/http_protocol.py", line 178, in process "server": self.server_addr, File "/myproject-env/lib/python2.7/site-packages/asgi_rabbitmq/core.py", line 812, in send future = self.thread.schedule(SEND, channel, message) File "/myproject-env/lib/python2.7/site-packages/asgi_rabbitmq/core.py", …