Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Key Error: 'Secret_Key' cant run server in django
Hello i just downloaded an open source Django CRM. Im using VSCode. Installed all the requirements in the dir and inside the venv. When I try to run the server there is a KeyError. These are the final lines that the error comes with: File "C:\Users\stani\OneDrive\Desktop\Ladyfit Site\Django-CRM-master\crm\settings.py", line 12, in SECRET_KEY = os.environ["SECRET_KEY"] File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\os.py", line 679, in getitem raise KeyError(key) from None KeyError: 'SECRET_KEY' From what I can see the Secret_key is in the env file. In settings.py the key is called with SECRET_KEY = os.environ["SECRET_KEY"]. I dont seem to see the problem and I read a ton of fixes today that dont fix it :). Please help. -
Django translation flags
I am trying to show flags using django-translation-flags in my app but this is showing me both languages' flags. How to configure this app so it shows only active language. {% load i18n flags %} <div class="translation"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} <ul> {% for lan in languages %} {% if lan.code != LANGUAGE_CODE %} <li class='cur-lan' ><a href="/{{lan.code}}{{request.path|slice:'3:'}}">{{lan.name_local}} </a></li> {% languages %} {% endif %} {% endfor %} </ul> </div> -
How can i count list of value from another model in Django?
I have two models and one of them contain a list of values that I want to count in another model. query1= list(Model1.objects.filter(CUSTOMER=customer.id).values_list("NAME",flat=True)) print(subquery) # [{'test1','test2,'test3','test4'}] response of query query2=list(Model2.objects.values('CUSTOMER_NAME').annotate(Count(subquery))) Is it possible to create all of that in one query set ? To keep the server running smoothly NB:If one of value does not exist the second model the query should return 0 for the count of this value Example of the return that i want to receive : [{'name':'test1','count':7}, {'name':'test2','count':4}, {'name':'test3','count':0}, {'name':'test4','count':0}, {'name':'test5','count':2}, {'name':'test5','count':4}] -
Django from Submit button doesn't do anything
I'm new to Django, and I'm trying to submit a form to process the data in a view function, but I can't find why when I press the Send button it doesn't do anything. i read many other questions but were syntax related problems, which I believe is not my case. Here's my form. It is in the new.html template: <from action="{% url 'notes:create' %}" method="post"> {% csrf_token %} <input type='text' name='note_name' id='note_name' placeholder='Title...'> <input type='date' name='note_date' id='note_date'> <input type="submit" value="Send"> </form> Here it is urls.py: app_name = 'notes' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('new/', views.new_note, name='new'), path('output/', views.create_note, name='create') ] And here the views.py file. Currently the create_note view only redirects to the index. I'm going to process the entered data once the form works correctly. class IndexView(generic.ListView): template_name = 'notes/index.html' context_object_name = 'all_notes' def get_queryset(self): return Note.objects.all() def new_note(request): return render(request, 'notes/new.html') def create_note(request): return HttpResponseRedirect(reverse('notes:index')) -
saving form data into csv in django- How to store data into csv file taking from html form in django
here are my views.py. I want to save my HTML form data into a CSV file. But my code is not working, this code shows no error. can anyone solve my issues? views.py import CSV result = 0 a1=0 a2=0 a3=0 a4=0 list = [] if request.POST.get('suu1'): a1 = request.POST['a1'] a2 = request.POST['a2'] a3 = request.POST['a3'] a4 = request.POST['a4'] a4=(str(a4)) a3=(str(a3)) a2=(str(a2)) a1=(str(a1)) # # try: # # result = eval(a1) + eval(a2) + eval(a3) + eval(a4) # print(result) # except: # result = 0 # print(result) try: with open('activityV3.csv', 'w+') as file: myFile = csv.writer(file) # myFile.writerow(["Id", "Activity", "Description", "Level"]) activityID = a1 activity = a2 desc = a3 level = a4 print(activityID,activity,desc,level) myFile.writerow([activityID, activity, desc, level]) except Exception as e: print('file error :', e) context = { 'result': result, 'a1':a1, 'a2':a2, 'a3':a3, 'a4':a4, } return render(request, "test.html", context) my form is working fine but data is not saving into CSV. I tried the above code in my project. but the data is not saved in the CSV file. But the HTML form is working very well. my main focus is to store data in CSV files taken from the form. thanks all. -
How to use gunicorn django and procfile with nested dirs?
The project structure goes like back\ |anwis\ | |anwis\ | |... | |wsgi.py |dg.sqlite3 |manage.py |... |venv\ | |... |Procfile |... In that Procfile i tried various things like web: gunicorn anwis.wsgi or web: gunicorn anwis.anwis.wsgi But somehow it all ended up now working, it just says "ModuleNotFoundError: No module named 'anwis.wsgi'" and that's it, there's nothing left to do else, i figure out that it needs a relative path to the wsgi file, but what is it then? -
annotate model with aggregate state of manytomany field
I have a Stream that has permissions = ManyToManyField(Permission) Permission has a state field. If all of the state's permissions are True then annotate state with allowed=True, else annotate state with allowed=False from django.db import models class Permission(models.Model): name = models.CharField(max_length=10), state = models.BooleanField() class Stream(models.Model): permissions = models.ManyToManyField(Permission) p1 = Permission.objects.create(state=True) p2 = Permission.objects.create(state=False) s = Stream.objects.create(name='s') s.permissions.add([p1, p2]) s1 = Stream.objects.create(name='s1') s1.permissions.add(p1) s2 = Stream.objects.create(name='s2') s2.permissions.add(p2) # How can I do something like this? annotated_streams = Stream.objects.annotate(allowed={... all([p.state for p in permissions]) ...}) [(s.name, s.allowed) for s in annotated_streams] [('s', False), ('s1', True), ('s2', False)] -
Is there any more pythonic way to checkfor keys in an ordered dictionary in Django
type of data <class 'collections.OrderedDict'> if("a" not in data or "b" not in data or "c" not in data or "d" not in data or "e" not in data or "f" not in data or "g" not in data or "h" not in data or "i" not in data): raise serializers.ValidationError("All Required Parameters not provided") i am checking for all these parameters whether they are present in my ordered dictionary or not is there any better way to check this? -
This page isn’t working. 127.0.0.1 didn’t send any data. Django
I am new to Django, trying to create a REST API with Django REST Framework. But, I have a problem when trying to run the server. Is there any problem in my manage.py file? I really need help. [These are the folders in VS Code][1] [I follow exactly like the tutorial.][2] [It said 127.0.0.1 didn't send any data.][3] [1]: https://i.stack.imgur.com/5TLYA.png [2]: https://i.stack.imgur.com/gRxk1.png [3]: https://i.stack.imgur.com/w8Cur.png -
Other Django Field Lookups for DurationFields?
I have a dynamic advanced search interface implemented in Django and javascript where the user selects: a field, a comparator (using a field lookup such as "iexact", "startswith", "gt", "lte", etc.), and a search term for any number of fields in the database Currently, for the 2 duration fields we have (age and "sample collection time (since infusion)"), the user is required to enter their search term in a format compatible with the timedelta used for django's database query, e.g. d-hh:mm:ss, foir the search to work properly. What we would like to do is accept search terms in the units in which the data is entered in the database (age in weeks and time collected in minutes). I could of course write one-off code to accomplish this, but I want this advanced search module I've written to be a generic implementation, so we can apply it to other projects without changing any code... So I was looking at the django doc's field lookups, which doesn't appear to have lookups for duration fields, but it links to a doc that gives advice on writing custom field lookups. There are definitely a few ways I can think of to do this, but … -
Change Data source in PowerBI according to userid entered in django html form
I am developing a web app in Django which takes user information and an excel file as input(the user fills out a form and uploads an excel file). The data from that excel file is extracted and stored in an SQL database. The extracted data is fed to an optimization model which produces a result that is stored in a separate excel file in an Amazon S3 bucket. The naming of the output excel file is unique(name contains userid). I want my PowerBi dashboard to connect to the output file depending on who is logged in to the Django web app ie get the userid from the web app search if the file containing that userid is present in the Amazon S3 bucket and if it is, connect that excel file to PowerBi dashboard, then embed that dashboard to a separate web page in Django, so that the specific user can see the visualizations. I went through multiple Powerbi articles, I know we can connect files in S3 to Powerbi using a custom python script, but don't know how to do it dynamically or even how to get the userid from the form and search the S3 bucket. Can anyone … -
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 …