Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can user download database from django heroku?
I make a apllication in django. I want put a download button in the my aplicattion. User can download then in this button. In local host this work, but when i put in heroku don't. listar.html: <p> <form method="POST"> <a href="{% url 'baixa' %}" download>Download</a> </form> <a class="btn btn-outline-primary" href="{% url 'cadastrar_colecao' %}">Adicionar Novo</a> </p> urls.py: urlspatterns = [ path('download/',Download.Download,name='baixa'), ] views.py: class Download(TemplateView): def Download(self): conn = sqlite3.connect('db.sqlite3') db_df = pd.read_sql_query("SELECT * FROM formulario_colecao", conn) db_df.to_csv('formulario/colecao_UFMGAC.csv', index=False) return FileResponse(open('formulario/colecao_UFMGAC.csv', 'rb'), as_attachment=True) In local host this work and my database system sqlite3. Heroku datase system is postgree -
Bootstrap grid not aligned properly
With the django framework I use a loop in my templates to display the image inside my database, I also use the Bootstrap grid to make it clean, but it not working correctly. As you can see the image on at the bottom are not align correctly. hmtl <div class="container"> <div class="row"> <div class="col-sm-12 col-md-3 col-lg-2"> <div class="card-filter" style="width: 10rem;"> <div class="card-header"> Pattern Type </div> <ul class="list-group list-group-flush"> {% for pattern in categories %} <li class="list-group-item">{{pattern.name}}</li> {% endfor %} </ul> </div> </div> {% for photo in photos %} <div class="col-sm-12 col-md-5 col-ld-5"> <div class="card" style="width: 25rem;"> <img class="card-img-top" src="{{photo.image.url}}" alt="Card image cap"> <div class="card-body"> <p class="card-text">Symbol: GBPUSD<br>Pattern: ButterFly Bullish</p> <a href="{% url 'photo' photo.id %}" class="btn btn-dark">View Pattern</a> </div> </div> </div> {% endfor %} </div> </div> views.py def home(request): categories = Category.objects.all() photos = Photo.objects.all() context = {'categories': categories, 'photos': photos} return render(request, "main/home.html", context) -
Django: Incompatible architecture after installing GDAL
I currently running Python 3.9.0 and trying to install gdal onto my system. My approach was very basic. First I entered this into my terminal: brew install gdal After that was done, I pip installed in the same terminal: ARCHFLAGS="-arch x86_64" pip3 install gdal --compile --no-cache-dir Checked the version: gdal-config --version 3.5.2 opened .zshrc text file and added the file paths: export GDAL_LIBRARY_PATH='/opt/homebrew/Cellar/gdal/3.5.2_1/lib/libgdal.dylib' export GEOS_LIBRARY_PATH='/opt/homebrew/Cellar/geos/3.11.0/lib/libgeos_c.dylib' Finally, When I run my project using an env, I get this response in my terminal. Blockquote OSError: dlopen(/opt/homebrew/Cellar/gdal/3.5.2_1/lib/libgdal.dylib, 0x0006): tried: '/opt/homebrew/Cellar/gdal/3.5.2_1/lib/libgdal.dylib' (mach-o file, but is an incompatible architecture (have (arm64), need (x86_64))), '/opt/homebrew/Cellar/gdal/3.5.2_1/lib/libgdal.31.dylib' (mach-o file, but is an incompatible architecture (have (arm64), need (x86_64))) -
Best approach to assigning existing data to a new django user
I am new in Django and I wanted to know what is the right approach to the following problem: I have a table of companies, which is m2m with the table of users. Since they can be created by the users. So what I want to do is, every time a user is created, I take a "default" company with a certain id and copy it to this new user. This way the user will be able to make the changes he wants in this company without affecting the original one that is being copied. -
I am trying to run a standalone Django script but i keep getting this error: ModuleNotFoundError: No module named 'django'
import os import django import sys import csv from collections import defaultdict sys.path.append('/Users/apple/Documents/COMPUTER-SCIENCE/ADV-WEB-DEV/Topic-files/topic2') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bioweb.settings') django.setup() Error: import django ModuleNotFoundError: No module named 'django' (venv) (base) apple@apples-MacBook-Pro topic2 % -
No module named 'social_django'
I have installed django and tried running the below command pip install social-auth-app-django But am still getting an error while installing the social auth. Installing build dependencies ... error error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> [41 lines of output] Collecting setuptools!=60.9.0,>=40.6.0 Using cached setuptools-65.5.0-py3-none-any.whl (1.2 MB) Collecting wheel Using cached wheel-0.37.1-py2.py3-none-any.whl (35 kB) Collecting cffi>=1.12 Using cached cffi-1.15.1.tar.gz (508 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error python setup.py egg_info did not run successfully. exit code: 1 I have searched on net, but not able to get a solution. Any help is appreciated!! -
Create a model method for a shared app based on project?
I can't seem to figure out a good solution to this issue: I've got an app that has a shared User model (AbstractUser) This app is shared among multiple projects (which all have their own apps) The structure looks like something like this: Project X App A App B Project Y App A App C App D Project Z App A App E App F I'm at a point where I need to add a model method on the User model in Project Z to make life easier. It would do some business logic involving other models from the other related apps in Project Z. I cannot add that method directly to the User model, because then the other projects would fail - since they would not contain all the referenced models. What is the best way to accomplish this in Django? Should I make a ProjectZUser that inherits the shared User model and add the methods on that model? -
How to complete the following task in django orm
I have two models. one is Author and the other is Book. an author can have multiple books. so the id of the author is the foreign key. and I have the following data. Author Table id Author Name 1 Tom Books Table id Author Book Name 1 1 rescue a person 2 1 be a doctor I want to create a function to get the following result when I query the author record. id author name books name 1 Tom rescue a person, be a doctor -
related_name foreign key doesn't show on template django
i have 2 models and i use related_name for one of them : memory model: class Memory(models.Model): memory_title=models.CharField(max_length=200,verbose_name='عنوان خاطره') memory_text=models.TextField(verbose_name='متن خاطره') register_date=models.DateField(default=timezone.now,verbose_name='زمان ثبت خاطره') is_active=models.BooleanField(default=False,verbose_name='فعال/غیرفال') user_registered=models.ForeignKey(User,on_delete=models.CASCADE,verbose_name='کاربر ثبت کننده') memory gallery model: class MemoryGalley(models.Model): memory_image_name= models.ImageField(upload_to=upload_gallery_image, verbose_name='تصویر خاطره') memory=models.ForeignKey(Memory,on_delete=models.CASCADE,null=True,related_name='pics') and fuction for upload image: def upload_gallery_image(instance,filename): return f"images/memory/{instance.memory.memory_title}/gallery/{filename}" views.py: class ShowmMemries(View): def get(self,request,*args, **kwargs): memories=Memory.objects.filter(is_active=True) if request.user.is_authenticated: list_memory_liked=MemoryLike.objects.filter(user_liked_id=request.user.id).values("memory_id") list_memory_liked_id=[memory["memory_id"] for memory in list_memory_liked] return render(request,'MemoriseFerdowsApp/showmemory.html',context={'memories':memories,'list_memory_liked_id':list_memory_liked_id}) return render(request,'MemoriseFerdowsApp/showmemory.html',context={'memories':memories}) and html file : {% for image in memory.pics.all %} <div class="carousel-item"> <img src="{{image.memory_image_name.url}}" class="d-block w-100" alt="..."> </div> {% endfor %} my problem is all images doesn't show in html files. in html file but in inspect there are address of images. how can i fix this problem ? -
Add custom HTTP header to Django application
I'm new to Django. I need to add this header to my Django app x-frame-options: SAMEORIGIN app/middleware.py from django.http import HttpResponse from django.utils.deprecation import MiddlewareMixin class HealthCheckMiddleware(MiddlewareMixin): def process_request(self, request): if request.META["PATH_INFO"] == "/elb-status/": request['x-frame-options'] = "SAMEORIGIN" # I've tried return HttpResponse("pong!") -
When I try to create a new PyDev Django Project I get this erroR
When I try to create a new PyDev Django Project ON ECLIPSEenter image description here I get this error: Error creating Django project. settings.py file not created Stdout: Stderr:enter image description here -
Django modelformsets contain no POST data
I have the following model models.py class Activity(Model): user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) activity = CharField(max_length=100, default='') number = IntegerField(default=1) and the following modelform forms.py class ActivityForm(ModelForm): class Meta: model = Activity fields = ['activity'] Made into a modelformset in the view views.py activities = Activity.objects.filter(user=request.user) ActivityFormSet = modelformset_factory(Activity, form=ActivityForm) formset = ActivityFormSet(queryset=activities) if request.method == 'POST': if 'save' in request.POST: formset = ActivityFormSet(request.POST) if formset.is_valid(): My view stops here. Because the formset is not valid, and formset.errors gives me: [{'activity': ['This field is required.'], 'id': ['This field is required.']}, {}] from my template: <form enctype="multipart/form-data" method = "POST"> {% csrf_token %} {{ form2.management_form }} {% for hidden in form2.hidden_fields %} {{ hidden }} {% endfor %} {% for activity in activities %} <div class="expandable-input-small" id="input_activity{{ activity.number }}" contenteditable="true"></div> <div id="form_activity{{ activity.number }}">{% for hidden in formset.form.hidden_fields %}{{ hidden }}{% endfor %}{{ formset.form.activity.as_hidden }}</div> {% endfor %} <button name="save" class="btn btn-primary" type = "submit" value = "Click" onclick="get_data()">Save</button> </form> I use javascript to transfer data from the contenteditable to the hidden formset form field before submitting with the function get_data(). I have tested and confirmed that this function works by calling it outside the form and setting the input fields as … -
Can I download a file into specific folder in user machine (python)?
I have been looking for information about that, but I haven't find a solution. Can someone help me pls??? I want to make the browser save the downloaded file into a specific folder at the user computer. Thank you very much. -
I can't run tests in Django, I'm getting the error, "Got an error creating the test database: permission denied to create database"
I'm really new to django, in fact this is my first project for a course I'm doing. I've finished it, but I still need to run tests. I've created one test, tried to run it, and this error came up: "Got an error creating the test database: permission denied to create database" From my understanding of researching the problem so far, the problem is that the user doesn't have permission to create the temporary test database. But I don't understand, because on Django admin I have logged in as the superuser. Shouldn't they have access? I've read I can use the command ALTER USER conorg180 CREATEDB. But I've tried this in the python shell and it's not working, it says that I have a syntax error. I'm not sure if the username is right. My superuser is called conorg180. However, I'm not sure if I need to use the superuser username or a different username, like one registered to the database. I don't have a username property on my database, because I have it set up using dj-database-url and postresql, you can see below. Is there a way I can find out the user property to get this command to … -
How to persist sqlite3 db in project folder when using Docker
I have a small project that me and another person are working on. The application is gathering some data and stores it in a sqlite db (located in ./data/db.sqlite3 ) that we want to keep and exchange through our git repo along with all the rest of the project code. When I try to dockerize the app, sure on each of our machines the data persists, yet not in the project folder itself. This is the docker-compose.yml: version: "3.8" services: gcs: build: . volumes: - type: bind source: ./data target: /data ports: - "8000:8000" And here is the Dockerfile itself: FROM python:3.8-slim-buster WORKDIR /gcs COPY requirements.txt requirements.txt RUN apt-get update && apt-get install nginx vim binutils libproj-dev gdal-bin -y --no-install-recommends RUN pip3 install -r requirements.txt COPY . . CMD python3 manage.py runserver 0.0.0.0:8000 Somehow I would say that the above mounts the 'data' folder in our projects folder to a data folder in the container. When I use docker inspect to see what's up there - it all seems fine, the source folder perfectly corresponds with my project db location: "Mounts": [ { "Type": "bind", "Source": "/Users/rleblon/projects/gcsproject/data", "Destination": "/data", "Mode": "", "RW": true, "Propagation": "rprivate" } Yet somehow the persistent … -
for message in messages: TypeError: 'Messages' object is not iterable
Am having issues with looping through an object here is my code from django.contrib.auth import get_user_model import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import Messages User = get_user_model() class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): messages = Messages.last_30_messages() content = { 'messages': self.messages_to_json(messages) } self.send_chat_message(content) def new_messages(self, data): sender = data['from'] author_user = User.objects.filter(username=sender)[0] message = Messages.objects.create(sender=author_user, msg=data['message']) content = { 'command': 'new_messages', 'message': self.messages_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.messages_to_json(message)) return result def message_to_json(self, message): return { 'sender': message.sender.username, 'msg': message.msg, 'timestamp': str(message.timestamp) } command = { 'fetch_messages': fetch_messages, 'new_messages': new_messages } def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_link"] self.room_group_name = "chat_%s" % self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): data = json.loads(text_data) self.command[data['command']](self, data) def send_chat_message(self, message): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type": "chat_message", "message": message, } ) def send_message(self, massage): self.send(text_data=json.dumps(message)) def chat_message(self, event): message = event["message"] self.send(text_data=json.dumps(message)) -
Error when django import rpy2 but OK with single python file (NotImplementedError)
import rpy2.robjects as robjects import rpy2.robjects.packages as rpackages from rpy2.robjects.vectors import StrVector packageNames = ('afex', 'emmeans') utils = rpackages.importr('utils') utils.chooseCRANmirror(ind=1) packnames_to_install = [x for x in packageNames if not rpackages.isinstalled(x)] # Running R in Python example installing packages: if len(packnames_to_install) > 0: utils.install_packages(StrVector(packnames_to_install)) data = robjects.r('read.table(file ="R.appendix3.data", header = T)') data.head() afex = rpackages.importr('afex') model = afex.aov_ez('Subject', 'Recall', data, within='Valence') emmeans = rpackages.importr('emmeans', robject_translations={"recover.data.call": "recover_data_call1"}) pairwise = emmeans.emmeans(model, "Valence", contr="pairwise", adjust="holm") print(pairwise) The python file imports rpy2 to use the function of r package. It's OK, but an error is occured in the Django framework (same code). NotImplementedError at /myapp/test/ Conversion 'rpy2py' not defined for objects of type '<class 'rpy2.rinterface.SexpClosure'>' What can I do to prevent it from happening? I want to implement the r package on the web under django.Thanks so much. -
Django doesn't render validation error of custom form validator
So I have the following form class SignUpForm(UserCreationForm): email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={ 'class': tailwind_class })) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) company_id = forms.CharField(label='Company Identifier', widget=forms.PasswordInput(attrs={'class': tailwind_class})) class Meta: model = get_user_model() fields = ('email', 'password1', 'password2', 'company_id') # Custom validator for the company id def clean_company_id(self): company_id = self.cleaned_data['company_id'] if not Company.objects.get(id=company_id): raise ValidationError("This Company ID doesn't exist") # Return value to use as cleaned data return company_id whose validator works except of displaying the error message in case it doesn't validate. That's my template: <form class="form shadow-2xl min-w-[360px] max-w-[360px] p-4 bg-woys-purple rounded-lg text-white" method="post" action="."> {% csrf_token %} <div class="error-wrapper mb-2"> <div class="errors text-woys-error-light text-center">{{ form.errors.email }}</div> <div class="errors text-woys-error-light text-center">{{ form.errors.password2 }}</div> <div class="errors text-woys-error-light text-center">{{ form.non_field_errors }}</div> </div> ... -
Django superuser not allowed to edit this model
Since recently I need to work home, but Django is working against me. I'm having a very peculier issue. I clone the repo, create a MySQL schema, migrate, dump all the data from the server into my local db so I have something to work with, start the server and I log in as the superuser. Now this is basically a job vacancy app for our company. These are my models: Status Department Location Contactperson Vacancy Applicant I can edit entries for anything not related to a department, which are statuses, locations or contacts. But when it comes to the rest, I get a error messsage saying my user is not allowed to edit these. An applicant is related to a vacancy which is related to a department, so I get the error message at all of these. class DepartmentAdminForm(ModelForm): prepopulated_fields = {'slug': ('name',)} readonly_fields = ['banner_image', 'button_background_image_location'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) self.obj = kwargs.pop('obj', None) super(DepartmentAdminForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() if self.instance.pk is None: # add return cleaned_data cleaned_data = super().clean() user = self.request.user is_authorized = department_role_check(self.obj, user) if is_authorized: return cleaned_data else: raise forms.ValidationError('You are not allowed to edit this department.') … -
Django authentication no longer works over HTTPS with custom domain
I have a django app deployed in a docker container in an azure appservice. It works fine on the provided URL: https://xxxx.azurewebsites.net I then set up a custom domain through azure using a cname xxxx.mysite.com. I verified the domain, and then purchased an SSL cert through azure and bound it to my custom domain. Now the app pulls up to the login screen, but authentication fails. I am not sure what I am missing. I also cannot figure out how to access any HTTP or nginx logs with in the app service. docker-compose.yml version: '3.4' services: myapp: image: myapp build: context: . dockerfile: ./Dockerfile ports: - 8000:8000 - 443:443 Dockerfile # For more information, please refer to https://aka.ms/vscode-docker-python FROM python:3.9-buster EXPOSE 8080 EXPOSE 443 # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 # Install pip requirements RUN pip install mysqlclient COPY requirements.txt . RUN python -m pip install -r requirements.txt WORKDIR /app COPY . /app # Creates a non-root user with an explicit UID and adds permission to access the /app folder # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers RUN adduser -u 5678 --disabled-password --gecos … -
Just updated to Django 4.0 and getting CSRF errors
What is the issue here. I have just updated to django 4 and on prodduction I am getting 403 csrf errors: Here are my settings: ALLOWED_HOSTS = [ '127.0.0.1', 'localhost', "https://exactestate.com", 'app', # '.ngrok.io' ] # '.ngrok.io', 'app' ALLOWED_ORIGINS = ['http://*', 'https://*'] CSRF_TRUSTED_ORIGINS = ALLOWED_ORIGINS.copy() The error is simply: Origin checking failed - https://exactestate.com does not match any trusted origins. -
Same FilterSet acts differently in two places
I use the same filterset_class for filtering results in FE, and for excel report generation. In FE everything works well, results are filtered correctly, buit for excel generation, the period filter is not applied. While debugging I see the period filters is available in the filter_args (see comment in bottom code block), but are not applied: count(logs) should be 1, but is 17. So something happens between declaring filter_args and logs in get_serialized_data, but have not been able to figure out what. Any ideas? views.py class LogFilterSet(FilterSet): model_names = [t.target_class._meta.model_name for t in ALLOWED_SELECTION_TARGET_MODELS] employee = NumberFilter(field_name="owner__id") company = NumberFilter(field_name="owner_company__id") period = CustomIsoDateTimeRangeFilter(field_name="start") class LogViewSet(viewsets.ModelViewSet): queryset = Log.objects.prefetch_related("selections").reverse().with_add_data() serializer_class = LogSerializer filter_backends = (DjangoFilterBackend,) filterset_class = LogFilterSet search_fields = None def get_queryset(self): queryset = super().get_queryset() if self.action in ["list", "detail"]: return queryset.for_role(self.request.role) return queryset.writable_for_role(self.request.role) CustomIsoDateTimeRangeFilter in utils.py class CustomMultiWidget(MultiWidget): def __init__(self, attrs=None): widgets = () super().__init__(widgets, attrs) def value_from_datadict(self, data, files, name): return data.getlist(name) if isinstance(data, QueryDict) else [] class CustomIsoDateTimeRangeField(IsoDateTimeRangeField): widget = WaybillerMultiWidget class CustomIsoDateTimeRangeFilter(RangeFilter): field_class = IsoDateTimeRangeField Filtered queryset for excel generation: def get_serialized_data(self): logs = ( Log.objects.prefetch_related("selections") .for_role(self.request.role) .with_add_data() .reverse() ) if filter_args := self.request.kwargs.get("filters"): # {'period': ['2022-09-06T21:00:00.000Z', '2022-09-07T20:59:59.000Z'], 'employee': 36} _filter = LogFilterSet(data=filter_args, queryset=logs) if not … -
Missing @property functions from metaclas in my Enum, what am I doing wrong?
I don't really like an implementation detail from Django's ChoicesMeta so I wanted to create my own enum metaclass that would fix that behaviour. In essence, this is what I wrote: from django.db.models.enums import ChoicesMeta as DjangoChoicesMeta class ChoicesMeta(DjangoChoicesMeta): def __new__(metacls, classname, bases, classdict, **kwds): # Here the code to fix the behavior I don't like return super().__new__(metacls, classname, bases, classdict, **kwds) class ChoiceEnum(Enum, metaclass=ChoicesMeta): pass class SomeEnum(ChoiceEnum) ONE = "some enum value 1" TWO = "some enum value 2" But then, when I wanted to use the property .choices that comes from django.db.models.enums.ChoiceMeta, I get an AttributeError: File "/usr/lib64/python3.10/enum.py", line 437, in __getattr__ raise AttributeError(name) from None AttributeError: values even though I can access to the property .__members__ that comes from ChoiceMeta's parent EnumMeta. Cant someone tell me what I'm doing wrong? -
Having trouble using javascript to create dynamic URL's with django for dates
Currently I have two basic routes: urlpatterns = [ path('<int:tutor_id>/', views.tutorHomeOverviewPage, name='tutorHomeOverviewPage'), path('<int:tutor_id>/<str:selected_date>/', views.tutorSelectedDay, name='tutorSelectedDay'), ] These routes point to two views which just get data from the database and send it to the template. The views work without any issues. My issue seems to lie with the URL that is being created in my JS files. So I have a calendar that dynamically gets list elements from a javascript for days that look like this: <a href="2022-10-14" id="day14">14</a> When I am at the URL - http://127.0.0.1:8000/tutorhomepage/7/ (which matches the first URL path) and I click on one of the days (so let's say the anchor element above), it goes to the correct URL: http://127.0.0.1:8000/tutorhomepage/7/2022-10-14/ However, when I click on another day while at http://127.0.0.1:8000/tutorhomepage/7/2022-10-14/, it just adds a second date to the URL like so - http://127.0.0.1:8000/tutorhomepage/7/2022-10-14/2022-10-1 My javascript, which is creating the 'a href' links, looks like this in brief: aLink.setAttribute('href', currentYear + '-' + (currentMonth + 1) + '-' +dayCounter) Any idea why this is happening and a possible fix for it? -
mysql.connector imports through the python shell, but still throws error in python module
I have a simple python module test.py. Its content is: import mysql.connector When I run it, it gives this error: C:\xxx\Software\Website\django\Scripts\python.exe C:\xxx\Software\Website\django\MyDB\test.py Traceback (most recent call last): File "C:\xxx\Software\Website\django\MyDB\test.py", line 1, in <module> import mysql.connector ModuleNotFoundError: No module named 'mysql' Process finished with exit code 1 So it can't find mysql.connector. But when I go into the python shell (launched from the directory of test.py), running >>> import mysql.connector doesn't give any error. So the mysql.connector package must be installed, somewhere. How come running the python module gives an error, while running the same python instruction through the python shell doesn't?