Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I implement separate user authentication and models for two apps in django project?
In this django project I have two separate applications that I need to keep user account information separate. For example, if a person creates an account for app A, I need them to be able to make a separate account (with the possibility of using the same unique email for account creation) for app B. At this moment in time, it seems as though there is no way for me to handle having two separate auth models for two separate users. I am wondering what the django workaround for this might be, or if I am misunderstanding the problem in some way? Here is an example user model that would work for both application A and B, but would need separate tables or models for authentication and account creation: class GenericUser(AbstractUser): """abstract user class for user authentication""" firstname = models.CharField('First Name', blank=True, max_length=100) lastname = models.CharField('Last Name', blank=True, max_length=100) email = models.CharField('Email', unique=True, max_length=100) class Meta: permissions = ( ("some-permission", "some-description"), ) First I tried creating two separate user entities in the models.py file in my django project, however when I finished doing this, there was nowhere to put the second user model in the settings.py folder. This is where … -
Tailwind's default colors are not working, only white and custom colors
I am building a web application through the django framework and installed tailwind through this tutorial "https://django-tailwind.readthedocs.io/en/latest/installation.html" and it worked fine intitially. Now everytime I reload my project after closing vscode, my colors stop working. For an example, I'll be creating a new line of html and use: <body> <div class="bg-blue-400 font-bold p-4 text-4xl"> <h1>Hello</h1> </div> </body> and the background just goes immediately to white. I have tried uninstalling and reinstalling and checking my directories and everything and still no solution. I have also found that only my custom colors work when I reload into my project. -
Firefox requests are just stopped after some time empty status code
I have Django fetch request that takes some to time to finish it works fine on chrome but fails on chrome I tried different view on Firefox and made it wait some time with time.sleep() function test_time(request): for i in range(70): print(i) time.sleep(1) return HttpResponse("done") if i made the time less than 20 the view works fine more than that in 25-36 seconds the page just stops loading and the request shows no status code - timing 0ms - response: No response data available for this request -
Correct way to add image related info wagtail
I am setting up a simple site with the main purpose of having galleries of images. Using collections to group images and display them on a specific page is how I set it up first. However I am not sure what the recommended way is to add a description. My options I have tried are: Custom page This seems as the way to handle it, however I lose the nice feature of using collections to generate pages. This would mean I separate info of a image into a page model, fragmenting the image from the data. I see that creating a custom image is recommended, but I doubt it's for this purpose. Custom image model This allows me to add a description field completely replaces the image model since you can only have 1 image model afaik. In a webshop like site this seems suitable (price, reviews, stock etc.) but since this site focuses on the image specific it seems this kind of coupling is ok. Is the first option the way to handle this? Or how can I set this up so that a designer/user can tie data to a image without losing the base image or allow the … -
Best way not to violate the DRY principle here. Django/Class-based Views
Here is a view I used to download an excel document based off data that I have: class ExcelDownloadAllView(TemplateView): def get(self, request, *args, **kwargs): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="All_of_Projects.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('All Projects Data') # this will make a sheet named Users Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Username', 'First Name', 'Last Name', 'Email Address', 'Summary'] rows = BugTracker.objects.all().values_list('project_number','assignee','priority','status','summary',) for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response It works fine, but now I want to create another CBV with a different "row=" filter. What is the best way to do this using DRY principles? I tried something like. But the rows variable will get overwritten by the previous class. class ExcelDownloadOpenView(ExcelDownloadAllView): def get(self, request, *args, **kwargs): rows = BugTracker.objects.all().values_list('project_number','assignee', 'priority') return super().get(request, *args, **kwargs) Any suggestions without copying the entire method and replacing the rows variable? -
Couldn't able to load js and images in Django
Could not able to load any javascript files and imagesenter image description here instead of using global... also tried to use app level static but nothing changes enter image description here [enter image description here](https://i.stack.imgur.com/9Mlhd.png) enter image description here -
Django, getting data from another user (schema) in an Oracle 19 DB
I am using Django 4.1, Oracle 19 with the python package oracledb. I am logged in as user djangousr and the schema I am trying to get the data from is "user123" I am able to retrieve data in a file outside of Django with the same connection information. But in Django, I keep getting the same error. I hope you have a solution for me as I was not able to find anything elsewhere. Thank you. ORA-00942: table or view does not exist Below is the SQL from the debug screen that I am able to run fine in SQL developer. ('SELECT "USER"."USER_ID" FROM "user123.USER_TABLE"') I will also provide the model and the view: class SecurityUserData(models.Model): user_id = models.IntegerField(primary_key=True) user_name = models.CharField(max_length=100) user_password = models.CharField(max_length=100) user_first_name = models.CharField(max_length=30, blank=True, null=True) user_last_name = models.CharField(max_length=30, blank=True, null=True) class Meta: managed = False db_table = 'SEC_USER' And the view: def display_user_data(request): user_data = SecurityUserData.user123.all() return render(request, 'all.html', {'user_data': user_data}) -
Trouble deploying Django application with Celery to Elastic Beanstalk
I have a working django application deployed to Elastic Beanstalk. I am trying to add some asynchronous commands to it so am adding Celery. Currently I am running container commands through python.config in my .ebextensions. I have added the command: 06startworker: command: "source /var/app/venv/*/bin/activate && celery -A project worker --loglevel INFO -B &" to my python.config. When I add this command and try to deploy my elasticbeanstalk instance timesout and deployment fails. I have confirmed that connection to my redis server is working and my application can connect to it. Checking my logs in my cfn-init.log I see: Command 01wsgipass succeeded Test failed with code 1 ... Command 06startworker succeeded So I think that when adding the 06startworker command it is somehow interfering with my 01wsgipass command which runs fine when I dont have the start worker command. For reference my wsgi command is: 01wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' I'm at a bit of a loss on how to troubleshoot this from here. I'm finding the logs that I am getting are not very helpful. -
how to resolve error of Access to external web links been blocked by CORS policy in react
How do i resolve this issue that i am getting when trying to send a request to an enpoint that would then redirect to a payment popup page. THis is the full error that i am getting Access to XMLHttpRequest at 'https://ravemodal- dev.herokuapp.com/v3/hosted/pay/6f77ffaf62ea8eb1c3a5' (redirected from 'http://127.0.0.1:8000/api/payment/sam/152.00/desphixs@gmail.com/') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. and this also GET https://ravemodal-dev.herokuapp.com/v3/hosted/pay/6f77ffaf62ea8eb1c3a5 net::ERR_FAILED 200 (OK) NOTE: i have CORS header Configured in my backend application as that is what have been allowing me to send request to the backend api. Django Settings.py CORS_ALLOW_ALL_ORIGINS = True Django Traceback [03/Feb/2023 22:37:02] "GET /api/payment/Nell/152.00/jopimo@mailinator.com/ HTTP/1.1" 302 0 what is going on, and how can i go about fixing this? -
Return a render to a view from another function in django
I am making a simple web page. I have to ask for an input, define its type, make some processing and return a few values. I have two views, one that has a simple form asking for an input, and the other one: def processedframe(request): frame = request.POST['frame'] try: if frame.startswith('>RUS08'): try: # Frame procesing(a lot) return render(request, 'frame.html', {'values': values) except: return HttpResponse("Processing error") else: return HttpResponse("Invalid frame") except: return HttpResponse("Invalid input") The problem is that i have +30 frame types with diferent things to process. I want to make one extern function in other folder for each frame type, and return a render from the function. I have already tried to make a separate folder with the functions and import it into the views.py That worked fine, because it was able to enter to the frame processing for the function, but when i tried to return the render from the function, i got an error, because the views.py was not returning anything. I have also tried to render from the views.py but i was not able to acces to the values from the function. I have also tried putting the code to process the frame inside the processedframe … -
How can I revive the website in Google Cloud Services?
Our lab had a web-based tool that was running on Google Cloud services, specifically in "Cloud Run". When our accounting did not pay the bills, service was shut down. Now it is paid, and it seems that are 2 services running in cloud run, one for Django and other for login backend service. I have the source code for both backend and frontend, but I have no idea how to make the application online again in its previous link. In "Cloud Storage" we also seem to have multiple buckets, where I don't know if they do anything or not. I have 0 web development experience. If you have developed a web platform by using Typescript on front-end and django on backend, a help to how to deploy these source codes on Google Cloud that was already previously running would be really appreciated. I paid the bills and 2 services on the "Cloud Run" seems to be working. They have their own link where when I click them one directs me our login page (but when I login successfully it does not render any frontend), and other just directs me to Django Rest Framework Api Root. I want to understand how … -
Unable to make a POST fetch request using Django (with React/JS)
How to send data using a POST fetch request from React/JS to a Django server? I'm able to make a GET request, so the servers working in that regard. The error I get from the terminal is: [0] Forbidden (Origin checking failed - http://localhost:3000 does not match any trusted origins.): /hello/ [0] [04/Feb/2023 08:31:02] "POST /hello/ HTTP/1.1" 403 2569 The error I get from browser console is: Form.jsx:47 POST http://localhost:8000/hello/ 403 (Forbidden) First of all I installed npm install js-cookie and imported Cookies Fetch request import Cookies from 'js-cookie' ... const response = await fetch('http://localhost:8000/hello/', { method: 'POST', headers: { "X-CSRFToken": Cookies.get('csrftoken'), "Accept": "application/json", 'Content-Type': 'application/json' }, body: JSON.stringify({ some_data: 'some_value' }) }); const data = await response.text(); console.log(data); urls.py urlpatterns = [ path('hello/', views.hello_world, name='hello_world'), ] views.py def hello_world(request): if request.method == 'POST': # do something with the data posted data = request.POST # return a JSON response return HttpResponse("Success: ") return HttpResponse("Error: ") settings.py INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] # Tested using a combination of: CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = [ "http://localhost:3000", ] CORS_ALLOW_METHODS = ['POST'] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_METHODS = ( 'GET', … -
Sending Logs to GCP from Django DRF application
I am trying to access the logs from my django app in GCP logging. I have thus far been unsuccessful. Here is my logging config: client = gcp_logging.Client.from_service_account_json( json_credentials_path='logging_service_account.json') client.setup_logging() LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': {'format': '%(levelname)s : %(message)s - [in %(pathname)s:%(lineno)d]'}, 'short': {'format': '%(message)s'} }, 'handlers': { 'stackdriver': { 'formatter': 'standard', 'class': 'google.cloud.logging.handlers.CloudLoggingHandler', 'client': client }, 'requestlogs_to_stdout': { 'class': 'logging.StreamHandler', 'filters': ['request_id_context'], } }, 'filters': { 'request_id_context': { '()': 'requestlogs.logging.RequestIdContext' } }, 'loggers': { 'StackDriverHandler': { 'handlers': ['stackdriver'], 'level': "DEBUG" }, 'django.request': { 'handlers': ['stackdriver'] }, 'requestlogs': { 'handlers': ['requestlogs_to_stdout'], 'level': 'INFO', 'propagate': False, }, }, } I invoke the logs along the lines of: import logging logger = logging.getLogger('StackDriverHandler') class OrganisationDetail(generics.RetrieveUpdateDestroyAPIView): /// def patch(self, request, pk, format=None): try: /// if serializer.is_valid(): serializer.save() logger.info(f"PATCH SUCCESSFUL: {serializer.data}") return Response(serializer.data) logger.warning(f"PATCH Failed: {serializer.errors}") return JsonResponse(serializer.errors, status=400) except Exception as e: logger.error(f"PATCH Failed with exception: {e}") return JsonResponse({'error': str(e)}, status=500) In GCP, I set up a service account, enabled logging api and gave the SA write logs and monitor metrics permissions. I then made a secret to contain my service_account key, and in my cloud-build.yaml file I run a step like this: - name: gcr.io/cloud-builders/gcloud entrypoint: 'bash' … -
Django Form with multiple buttons
I have a form for a voting system. I have the candidates in a table row. At the end of the row I have button with the candidate ID <form method="post"> <table> ... <tr> <td>name</td> <td>campaign promises</td> <td><button id="candidate_id"></td> <tr> ... </table> </form> "candidate_id" is an actual number and unique. I would like to get that id value from the post request, so I know which candidate was selected. Im hoping its as simple as request.POST.Something -
Daemonizing celery with supervisor issues (Django Rest Framework)
I cannot seem to get celery working in production using supervisor. I am normally using it in local development running the command. However, when I make a supervisor setup, it is not working. Reading the logs I am getting the error: Unable to load celery application. The module inp_proj was not found. My .conf file for supervisor is: [program:inp_proj] directory=/www/[project_directory]/inp_proj command=/www/[project_directory]/venv/bin/celery -A inp_proj worker --loglevel=INFO user=jan numprocs=1 stdout_logfile=/var/log/celery/inp_proj.log stderr_logfile=/var/log/celery/inp_proj.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 this is my celery.py file: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'inp_proj.settings') app = Celery('inp_proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() It is located inside project directory and inside inp_proj. I tried changing the celery command in the created config file, adding environment path to supervisor config file but nothing seems to be working. If I manually active the venv with source venv/bin/activate and then start the worker manually, it works normally. But when using supervisor, it doesn't work. -
django-registration-redux and spurious migration from DEFAULT_AUTO_FIELD of BigAutoField
I installed django-registration-redux 2.11 into Django 4.1.6. When I run makemigrations, it makes a migration to change an id field to BigAutoField: # Generated by Django 4.1.6 on 2023-02-03 19:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("registration", "0005_activation_key_sha256"), ] operations = [ migrations.AlterField( model_name="registrationprofile", name="id", field=models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID" ), ), ] I suspect this is because DEFAULT_AUTO_FIELD is now BigAutoField as of Django 3.2, see here. However, it's creating a migration in my virtualenv, not under source code control: $ ./manage.py makemigrations Migrations for 'registration': .venv/lib/python3.10/site-packages/registration/migrations/0006_alter_registrationprofile_id.py - Alter field id on registrationprofile So that's not gonna work well. I don't want to change my DEFAULT_AUTO_FIELD to AutoField. I just want to change it for django-registration-redux I guess? I see that registration already has default_auto_field = 'django.db.models.AutoField', so I'm puzzled as to why Django is making this migration. I tried adding my own registration/apps.py into source code control with default_auto_field as AutoField, and that didn't work. Suggestions? I might just have to move to django-allauth or back to django-registration, as they suggest. -
How i get the value from a dictionary if the key from all keys are the same?
I wanna from a dictionary all values but i have for each value the same key. It is possible that i can get the values in a separately empty list? dic = QuesModel.objects.values("ans").distinct() print(dic) # i get: """<QuerySet [{'ans': 'antwort1'}, {'ans': 'answer2'}, {'ans': 'besitzt als Modelle elemente verschiedene Ereignistypen.'}, {'ans': 'als Nachrichten und Datenobjekte e dargestellt.'}, {'ans': '2 ist eine rationale Zahl'}, {'ans': 'x hat den Wert 5 5'}, {'ans': ''}]> """ and i wanna get the values from dic in a list, Like: for key, values in dic.items(): # but this doesn `t work How can i fixed that?? -
Request' object has no attribute 'get': Django Views &. Serializers
I am working on a Dajngo DRF app serving as the API for my app. I am really struggling to debug this error: Request object has no attribute 'get'. The error pops up after I update my organisation. The error is being caught as an exception, so I am fairly certain it is coming from the patch method of my OrganisationDetail view. Here is the view below: class OrganisationDetail(generics.RetrieveUpdateDestroyAPIView): """ Retrieve, update or delete an organisation. """ permission_classes = (IsAuthenticated, IsInOrg) queryset = Organisation.objects.all() serializer_class = OrganisationSerializer logger.info("Init log from organisation view") def get_object(self, pk): try: return Organisation.objects.get(pk=pk) except Organisation.DoesNotExist: return HttpResponse(status=404) def get(self, request, pk, format=None): organisation = self.get_object(pk) serializer = OrganisationSerializer(organisation) return Response(serializer.data) def patch(self, request, pk, format=None): try: organisation = self.get_object(pk) data = copy.deepcopy(request.data) member_to_remove = request.data.get( 'user_to_remove', 'no_user_to_remove') if member_to_remove != 'no_user_to_remove': data['member_to_remove'] = member_to_remove if "name" not in data: data["name"] = organisation.name if "description" not in data: data["description"] = organisation.description serializer = OrganisationSerializer( organisation, data=data, context=request, partial=True) if serializer.is_valid(): serializer.save() logger.info(f"PATCH SUCCESSFUL: {serializer.data}") return Response(serializer.data) logger.warning(f"PATCH Failed: {serializer.errors}") return JsonResponse(serializer.errors, status=400) except Exception as e: logger.error(f"PATCH Failed with exception: {e}") return JsonResponse({'error': str(e)}, status=500) I am also going to include my serializer in the hope … -
Django4.1.6 LOGIN_REDIRECT_URL is not working
I would like to be taken to the page after login. I want to login using the LoginView class, but the login page just reloads and does not take me to the page after login. The terminal says ("POST /accouts/login/ HTTP/1.1" 200 2467). Is the LOGIN_REDIRECT_URL not working? accounts/views.py from django.shortcuts import render, redirect from django.views import View from accounts.models import CustomUser from accounts.forms import ProfileForm, SignupUserForm from allauth.account import views class ProfileView(View): def get(self, request, *args, **kwargs): user_data = CustomUser.objects.get(id=request.user.id) return render(request, 'accounts/profile.html', { 'user_data': user_data, }) class ProfileEditView(View): def get(self, request, *args, **kwargs): user_data = CustomUser.objects.get(id=request.user.id) form = ProfileForm( request.POST or None, initial = { 'first_name': user_data.first_name, 'last_name': user_data.last_name, 'department': user_data.department, } ) return render(request, 'accounts/profile_edit.html', { 'form': form }) def post(self, request, *args, **kwargs): form = ProfileForm(request.POST or None) if form.is_valid(): user_data = CustomUser.objects.get(id=request.user.id) user_data.first_name = form.cleaned_data['first_name'] user_data.last_name = form.cleaned_data['last_name'] user_data.department = form.cleaned_data['department'] user_data.save() return redirect('profile') return render(request, 'accounts/profile.html', { 'form': form }) class LoginView(views.LoginView): template_name = 'accounts/login.html' class LogoutView(views.LogoutView): template_name = 'accounts/logout.html' def post(self, *args, **kwargs): if self.request.user.is_authenticated: self.logout() return redirect('/') class SignupView(views.SignupView): template_name = 'accounts/signup.html' form_class = SignupUserForm mysite/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'app', 'accounts', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', … -
Queryset for specific child class (NOT abstract model)
How do I get a queryset of specific child classes? It doesn't look like going through related_name is the answer. Using Django 3.2.6 btw. Here is my setup: class Quiz(models.Model): name = # char field class Question(models.Model): # a quiz has many questions quiz = models.ForeignKey(Quiz, related_name = '%(class)s') # etc... class TFQuestion(Question): is_true = models.BooleanField(...) class MCQuestion(Question): n_choices = models.IntegerField(...) What I want is to get a queryset of just MC Questions and process them as such. I feel the need to emphasize that Question is NOT abstract. So the question model has its own related_name but the specified '%(class)s' pattern does not seem to propagate down to the child classes. All the other threads I've seen suggest using that pattern but it only works for abstract models! not when using multi-table inheritance. From what I've seen, I can't just do: quiz1 = Quiz.objects.get(id=1) # this works; returns queryset of Question objects allquestions = quiz1.question.all() # doesn't work all_mcqs = quiz1.mcquestion.all() -
Is it good idea to use result of dump_bulk() method from django-treebeard instead serialization in Serializer or ModelSerializer classes in DRF?
I wanna to build e-commerce website with Django Rest Framework and React. In e-commerce websites there are nested categories. So I needed to build model which can works with hierarchical data.And I stopped at the Django treebeard library. I've chosen Materialized path algorithm for store hierarchical data. But I decided to practice with this library before developing my main project and I tried to do serialization with one query to the DB but I failed In Django treebeard there is dump_bulk() method which get all data from DB in one query (But if I use Nested sets it get all data in multiple queries) Is it good idea send result of dump_bulk()method with Response() object to client side? -
ValueError: Related model 'auth.user' cannot be resolved while migrating
I am trying to configure a project for pythonanywhere.com. I deleted an old sqlite3 file, as well as migrations, so now I want to restore it. I launched command py manage.py makemigrations, then I run py manage.py migrate. But there I got an error: Operations to perform: Apply all migrations: FriendsAnalyzer, account, admin, auth, contenttypes, sessions, sites, socialaccount Running migrations: Applying socialaccount.0001_initial...Traceback (most recent call last): File "/home/FarmerKarwer/VkAnalyzer/manage.py", line 22, in <module> main() File "/home/FarmerKarwer/VkAnalyzer/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/migration.py", line 130, in apply operation.database_forwards( File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/operations/models.py", line 96, in database_forwards schema_editor.create_model(model) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 444, in create_model sql, params = self.table_sql(model) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 216, in table_sql definition, extra_params = self.column_sql(model, field) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 348, in column_sql … -
csv file is not generating after I deployed ti pythonanywhere
I have my view which is generating csv file, but it doesn't work after I deployed my project to python anywhere Error: enter image description here view: `def generate_csv(request, pk): if request.method == 'POST': columns = models.Column.objects.all().filter(schema__id=pk) names = [None for _ in columns] types = [None for _ in columns] for column in columns: names[int(column.order) - 1] = column.name types[int(column.order) - 1] = column.type form = forms.DataSetForm(request.POST) fake = Faker() if form.is_valid(): rows = int(form['rows'].value()) schema = models.Schema.objects.get(id=pk) file_name = f'{schema.title}{fake.pyint()}.csv' file = open(f'media/{file_name}', mode='w', newline='') dataset = models.DataSet(schema=schema, csv_file=f'{file_name}') dataset.save() file_writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) file_writer.writerow(names) for _ in range(rows): data = [] for i in types: data.append(fake_data(i)) file_writer.writerow(data) file.close() dataset.status = True dataset.save() return JsonResponse({}, status=200) else: return JsonResponse({'error': form.errors}, status=400) return JsonResponse({'error': ''}, status=400)` I think the problem is that I have to create the csv file in a different way, but I don't know how, can you help me? -
Custom per-VIRTUAL_HOST location config without effect: 502 Bad Gateway
I try to setup a dockerized nginx reverse proxy server, which should supply a dockerized Gunicorn webserver with. The Gunicorn webserver shall be accessible through example.com/django so I added custom nginx directives, as described here: https://github.com/nginx-proxy/nginx-proxy/blob/main/README.md#per-virtual_host-location-configuration I placed the directives in a example.com_django/www.example.com_django file. However, they are not adopted in the main nginx config file and don't seem to have any effect. The website is not accessible and results in a 502 Bad Gateway error. Docker Compose files and the custom nginx config file are further below. Main ressources I used are: https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#project-setup https://github.com/nginx-proxy/nginx-proxy/blob/main/README.md https://docs.gunicorn.org/en/stable/deploy.html#nginx-configuration docker-compose.yml: NGINX Proxy version: "3.9" services: nginx-proxy: image: nginxproxy/nginx-proxy:alpine container_name: nginx-proxy volumes: - conf:/etc/nginx/conf.d - html:/usr/share/nginx/html - dhparam:/etc/nginx/dhparam - vhost:/etc/nginx/vhost.d:ro - certs:/etc/nginx/certs:ro - /var/run/docker.sock:/tmp/docker.sock:ro restart: always networks: - nginx-net ports: - 80:80 - 443:443 acme: image: nginxproxy/acme-companion:latest container_name: nginx-proxy-acme depends_on: - nginx-proxy volumes: - html:/usr/share/nginx/html - conf:/etc/nginx/conf.d - dhparam:/etc/nginx/dhparam - vhost:/etc/nginx/vhost.d:ro - certs:/etc/nginx/certs:rw - acme:/etc/acme.sh - /var/run/docker.sock:/var/run/docker.sock:ro environment: - NGINX_PROXY_CONTAINER=nginx-proxy - DEFAULT_EMAIL=account@domain.com restart: always networks: - nginx-net volumes: conf: certs: html: vhost: dhparam: acme: networks: nginx-net: external: true docker-compose.yml: Django Server version: '3.8' # Prod environment services: web: build: context: . dockerfile: Dockerfile command: gunicorn core.wsgi:application --forwarded-allow-ips="172.31.0.0/24,www.example.com,example.com" --bind 0.0.0.0:8083 expose: - 8083 env_file: - ./.env … -
Django ModelAdmin save method not executing
I have a custom ModelForm class and ModelAdmin class and for some reason my save_model method will not execute. Ill show both classes i currently have in admin.py. all functions (search, filter, hiding fields, delete) currently work correctly except for saving a new entry... here is my form: class SeasonalityOriginalsForm(forms.ModelForm): # defining the input fields that should be hidden class Meta: model = SeasonalitiesCalculated fields = '__all__' widgets = { 'has_been_reviewed': forms.HiddenInput(), 'user': forms.HiddenInput(), 'source_importance_0least_to_10most': forms.HiddenInput(), 'internal_id': forms.HiddenInput(), } ### this defines a dropdown selector field for object_id ### instead of copy-pasting the UUID from another adminmodel page, which could bring errors ### admins can now select the country or admin_zone_1 with the right granularity by selecting location name ### an issue is that this is a choicefield, not a model choicefield. ### this issue is solved in the save_model method in the ModelAdmin class. def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) logger.debug(f'self model info: {type(self.fields)}') countries = Countries.objects.filter(level_of_seasonal_area_granularity='country') admin_zones1 = AdminZones1.objects.filter(country__level_of_seasonal_area_granularity='admin_1') choices = [(obj.public_id, str(obj)) for obj in countries] + [(obj.public_id, str(obj)) for obj in admin_zones1] self.fields['object_id'] = forms.ChoiceField(choices=[]) self.fields['object_id'].choices = choices logger.debug(f'self model info2: {self.fields}') ### here are the visible input fields of the object_id = forms.ChoiceField(choices=[]) content_type = …