Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django GenericSitemap: Problem with the model
I'm trying to create a Django sitemap with the GenericSitemap function. my urls.py file looks like this: from django.urls import path from . import views from django.views.generic.base import TemplateView from re_analytics.models_new import AnalyticsData from django.contrib.sitemaps import GenericSitemap from django.contrib.sitemaps.views import sitemap sitemaps = { 'analytics': GenericSitemap({ 'queryset': AnalyticsData.objects.all(), 'date_field': 'timestamp', }, priority=0.9) } urlpatterns = [ ... path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] My models_new.py file looks like this: from django.db import models class AnalyticsData(models.Model): index = models.TextField(blank=True, null=False) post_code = models.FloatField(blank=True, null=True) ... Running the app works. I just have trouble accessing the sitemap view. I get the following error message: OperationalError at /sitemap.xml no such column: analytics_data.id Request Method: GET Request URL: http://127.0.0.1:8000/sitemap.xml Django Version: 3.2.5 Exception Type: OperationalError Exception Value: no such column: analytics_data.id Exception Location: /Users/finnj/coding/App1/env/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /Users/finnj/coding/App1/env/bin/python Python Version: 3.9.6 Python Path: ['/Users/finnj/coding/re_crawler_homepage/re_homepage', '/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/finnj/coding/App1/env/lib/python3.9/site-packages'] This messages indicates that the column id is not existing in the model. And yes it is not existing there. The 'local var' in the error message indicate the the app is trying to extract this column : sql ('SELECT "analytics_data"."id", "analytics_data"."index", ' '"analytics_data"."post_code",... How does it happen that the id column suddenly … -
Python regex for this type of number (xx-x-xxxx-x), for ex. 21-1-9999-4
Hello devs I want to validate this type of number 21-1-9999-4 using python regex format of regex like(xx-x-xxxx-x) Thanks for advanced -
version_info, _mysql.version_info, _mysql.__file__ NameError: name '_mysql' is not defined
import MySQLdb as Database File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/init.py", line 24, in version_info, _mysql.version_info, _mysql.file NameError: name '_mysql' is not defined -
AWS ElasticBeanstalk Stripe
I dont have a domain and i didnt configured my SSH(which i don't know what it's) I deployed Utilizing Elastic Beanstalk on local its working just fine, but deployed i cant load the stripe. Im utilizing live keys error: Uncaught IntegrationError: Live Stripe.js integrations must use HTTPS. For more information: https://stripe.com/docs/security/guide#tls at e.value ((index):1:312510) at new e ((index):1:281123) at No ((index):1:314058) at create:303:20 what can i do to correct this? -
How to put a constraint using foreign key fields in Django?
Consider following models: class Model1: x = an integer y = an integer class Model2: f1 = models.ForeignKey(Model1) f2 = models.ForeignKey(Model1) Now, I want to put a constraint on model 2 such that no duplicate pairs of f1.x and f2.x get inserted in model 2. How should I achieve it? I will be populating model 2 using bulk_create so maybe customising clean() or save() won't work. I'm new to Django and not able to figure it out. Any help will be appreciated. -
What's the mechanism behind a "print" statement that works as "if" statement?
Sorry, I can't find right words to describe my question. I'm already solved my problem. I just want to understand the mechanism under the hood. Basically, I have a calculated field based on the other two fields in Django. In my models.py, class Order(models.Model): quantity = models.IntegerField() price = models.IntegerField() In my admin.py, class OrderAdmin(admin.ModelAdmin): fields = ["quantity", "price", "get_total", ] readonly_fields = ["get_total", ] def get_total(self, obj): return obj.quantity * obj.price When adding new object in admin, it throws me TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'. I can solve it by changing the get_total method: def get_total(self, obj): if obj: return obj.quantity * obj.price However, I can also solve it by adding a print: def get_total(self, obj): print(obj) return self.quantity * self.price I found it during debugging. The results turned out with no difference. It didn't print anything in the console. What's the magic behind the print? By the way, I'm using Python 3.9.6 and Django 3.2.12. -
initial value of field modelform_factory in Django
This is my first post on StackOverflow. I'm also new to using Django (I'm actually using version 3.2). I have read about how to set the initial value of a field in a form using the initial parameter of a modelform_factory. I have followed several code examples but, the field does not display the value. My App uses the crispy_form plugin. The matricula field in my model is the one I want to set up with a value that is taken from a query getting the total number of records in the teacher table plus 1. When I load the page, the matricula field in the form does not display the desired value. what am I doing wrong? Thanks for your help. Sorry for my English. It is not very good. I hope you can understand me. Translated with www.DeepL.com/Translator (free version) This is my code: Model: class docente(models.Model): matricula = models.CharField(max_length=10, verbose_name="Matrícula", unique=True) nombre = models.CharField(max_length=80) apellidoPaterno = models.CharField(max_length=80, verbose_name=" Apellido Paterno") apellidoMaterno = models.CharField(max_length=80, verbose_name="Apellido Materno", blank=True) # Campo opcional direccion = models.CharField(max_length=150, verbose_name="Dirección", blank=True) # Campo opcional telefono = models.CharField(max_length=13, verbose_name="Teléfono", blank=True) # Campo opcional email = models.EmailField(verbose_name="Correo Electrónico", blank=True) # Campo opcional colonia = models.CharField(max_length=150, blank=True) … -
CK EDITOR image , table and vertical scroll bar issue issue
I have added CK EDITOR to textarea field on my webpage after adding CK Editor I got a Vertical Scroll bar. My problem is How to remove this scroll bar which I have Got after adding CK Editor. template code: <div class="container"> <form method="POST"> <div class="form-group"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4" style="font-weight: 700;">Create Notes</legend> </fieldset> {{form.media}} {{form|crispy}} <div class="form-group"> <button href="" class="btn btn-primary" type="submit"> Create </button> </div> </div> </form> model.py: title=models.CharField(max_length=200) description = RichTextField(blank=True,null=True) My second problem is I want to remove image ,table and anchor option from editor. please help me to fix both problems. thanks in advance -
Django high memory usage
I'm using django as a backend for a React frontend, and deploying both applications on Heroku. I use Gunicorn do serve the application and signed the Hobby plan on Heroku which offers 512 MB of RAM for the application to run. But the django dyno, is almost always using a lot of memory, and exceeding the 512 mb limit. It goes down to only 40 MB of usage whenever I restart or deploy changes, but as soon as any user uses the system and calls some queries. The memory goes up a lot. I've read about django and django-rest-framework memory optimization for some days now, and tried some changes like: using --preload on Gunicorn, setting --max-requests to kill proccess when they're too heavy on memory, i've set CONN_MAX_AGE for the database and WEB_CONCURRENCY as stated on: https://devcenter.heroku.com/articles/python-concurrency-and-database-connections But none of that gave me a good enough result. What I'm guessing is wrong now are my queries, because I've seen some articles about the usage of .iterator() on queries and how it prevents de queries from being cached by the application and I didn't use it in any of my queries. I don't think caching the queries would help on my … -
File download function not working in Django views.py
[supporting/views.py] def download(request): output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() merge_format = workbook.add_format({'align': 'center', 'valign': 'vcenter'}) supportings = Supporting.objects.filter(is_deleted='0') \ .annotate(date_str=Cast(TruncDate('in_date'), CharField())) \ .values_list('date_str', 'date_str', 'study_name', 'register_number', 'person_name', 'person__no', 'date_str', 'kinds', 'teacher', 'comment', 'technician') supportings = pd.DataFrame.from_records(supportings) supportings = supportings.rename(columns={0: 'Days', 1: 'Date', 2: 'Study name', 3: 'Register Number', 4: 'Name', 5: 'No', 6: 'Time', 7: 'Kinds', 8: 'Teacher', 9: 'Comment', 10: 'Technician'}) for supporting in supportings['Days'].unique(): # find indices and add one to account for header u = supportings.loc[supportings['Days'] == supporting].index.values + 1 if len(u) < 2: pass # do not merge cells if there is only one supporting Days else: # merge cells using the first and last indices worksheet.merge_range(u[0], 0, u[-1], 0, supportings.loc[u[0], 'Days'], merge_format) workbook.close() output.seek(0) supportings.set_index(supportings.columns[:-1].tolist()).to_excel('success.xlsx') The above code works normally in Jupyter notebook and the file is downloaded. However, when I run the above code in Django, there is no return value, so "The view supporting.views.downloaddidn't return an HttpResponse object. It returned None instead." An error occurs. So, I deleted the to_excel method and added the code as below. However, the file cannot be downloaded. No event occurs.. supportings.set_index(supportings.columns[:-1].tolist()) filename = 'Supporting_List.xlsx' try: filename.encode('ascii') file_expr = 'filename="{}"'.format(filename) except UnicodeEncodeError: file_expr = "filename*=utf-8''{}".format(quote(filename)) … -
How to search via Enums Django
I'm trying a write a search function for table reserving from a restaurant, I have a restaurant model: class Restaurant(models.Model): """ Table Restaurant ======================= This table represents a restaurant with all necessary information. """ name = models.CharField(max_length=70) caterer = models.ForeignKey(Caterer, on_delete=models.CASCADE, null=True) address = models.OneToOneField(Address, on_delete=models.CASCADE, null=True) kitchen_type = models.IntegerField(choices=KITCHEN_TYPE, null=True) opening_hours = models.OneToOneField(OpeningHours, on_delete=models.CASCADE, null=True) description = models.CharField(max_length=2000, null=True) phone = models.CharField(max_length=15, null=True) parking_options = models.BooleanField(default=False) which has a enum for kitchen_type: KITCHEN_TYPE = [ (1, "Turkish"), (2, "Italian"), (3, "German"), (4, "English"), (5, "Indian"), ] And this search function in view.py: def search_result(request): if request.method == "POST": searched = request.POST['searched'] result = Restaurant.objects.filter( Q(name__icontains=searched) | Q(address__city__icontains=searched)) return render(request, 'search_result.html', {'searched': searched, 'result': result}) else: return render(request, 'search_result.html', {}) So how am I able to search for kitchen_type in the view? -
How to run an existing Django application on aws ec2 instance?
I am trying to run a Django application on AWS Ec2 instance. I've chosen Ubuntu as my platform. After cloning the git repository, and creating a virtual environment, I have installed all apps in my requirements.txt. When I try to the following lines of code python3 manage.py migrate ; python3 manage.py check ; python3 manage.py runserver the following error is coming up. django.db.utils.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "columbus_db" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "columbus_db" My settings.py file looks like this 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Database Engine of PostgreSQL Database 'NAME': 'columbus_db', # Database Name 'USER': 'columbus_db', # Database has a Root User 'PASSWORD': 'columbus', # Database Connection Password 'HOST': "localhost", # IP Address for Localhost } What can I change in settings.py or Ec2 Instance settings to start the application and see it at Ec2 IP address? -
AttributeError Object has no attribute
getting AttributeError at /url/ 'SignUpForm' object has no attribute 'newsletter', when trying to sign up a new user #views from somewhere.views import subscribe def createaccount(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() if form.newsletter == True: email = request.POST['email'] subscribe(email) else: pass login(request, user) return redirect('main:home') #forms class SignUpForm(UserCreationForm): newsletter = forms.BooleanField(label="Subscribe to Newsletter", required=False) -
Integrity Error on DRF on fixture teardown
I have these 2 models in Django: class Invoice(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) owner = models.ForeignKey(to="User", on_delete=models.CASCADE) client = models.ForeignKey(to=Client, on_delete=models.CASCADE) project = models.ForeignKey(to=Project, on_delete=models.CASCADE) work_sessions = models.ManyToManyField (WorkSession) fixed_travels = models.ManyToManyField(FixedTravel) hourly_travels = models.ManyToManyField(HourlyTravel) class WorkSession(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) start_timestamp = models.IntegerField(editable=True, null=False, blank=False) end_timestamp = models.IntegerField(editable=True, null=False, blank=False) project = models.ForeignKey(to=Project, on_delete=models.CASCADE) owner = models.ForeignKey( to="User", related_name="work_sessions", on_delete=models.CASCADE ) I'm in the middle of an APITestCase in Django Rest Framework where I create 2 work sessions and one invoice and assign those sessions to the invoice Now on the fixture teardown, this exception gets thrown raise IntegrityError( django.db.utils.IntegrityError: The row in table 'drscm_invoice_work_sessions' with primary key '1' has an invalid foreign key: drscm_invoice_work_sessions.invoice_id contains a value '13ba348db35746c1b7f56884efc6249a' that does not have a corresponding value in drscm_invoice.id. What I want is for WorkSession to exist even though an Invoice gets deleted And it's not a ManyToOne relationship that I'm looking for :/ What am I doing wrong here ? -
How to integrate The Docker of Django and ReactJS with Kafka to generate some analytical data for users?
I'm implementing a Django web service, which is about to have different platform apps, Reactjs for computers, a swift app for ios, and Kotlin for android devices. the protocol is rest API and perhaps a chat feature included then Django channels are used as well. The data format is JSON. For deployment, I intend to use docker which includes Django, celery, and ReactJS app. And the database is on another separate server which is PostgreSQL. I was thinking to collect some user activity data and some history logs to show the user itself what she/he has done so far. After hours of searching, I came up with Kafka! unfortunately, I have no idea how can I use Kafka and integrate these stuff together and how can I deploy these things. I wish there was a system schema for this specific kind of system that shows what's what and what's where! -
Downloading Files From S3 To Users Computer
I have the following view in my Django project class download_mscore_software(APIView): def get(self, request): session = boto3.Session( aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY ) s3 = session.resource('s3') clancy = s3.Bucket("magpie-bixly-test").download_file("Clancy-Gorillaz.jpg", "Clancy-Gorillaz.jpg") This works to download the file into my project directory. However, I need the file to download to the users computer. How do I change this so that this happens? I tried this: clancy = s3.Bucket('magpie-bixly-test').download_file('Clancy-Gorillaz.jpg', 'Users/Downloads/Clancy-Gorillaz.jpg') but I get an error saying that there is no such directory. The same happens if I leave the file name off the end like this. clancy = s3.Bucket('magpie-bixly-test').download_file('Clancy-Gorillaz.jpg', 'Users/Downloads') -
Not allowed to call async on function converted with sync_to_async()
I am having problems with sync_to_async. I am getting the You cannot call this from an async context - use a thread or sync_to_async. error at the print statement, even though I used sync_to_async to convert the async function. If I do print(type(masters)) instead, i get a QuerySet as type. Is there something I am missing? I couldn't find this specific case on the docs. Here is my code: import discord from discord.ext import commands from asgiref.sync import sync_to_async class Bot(commands.Bot): # ... async def on_message(self, msg): masters = await sync_to_async(self.subject.masters)() print(masters) Here is the masters() function i'm trying to get results from: from django.db import models class Subject(models.Model): # ... def masters(self): from .subjectmaster import SubjectMaster return SubjectMaster.objects.filter(subject=self) -
how to delete many-to-many relations in django?
i'm trying to delete my m2m relation, i think i wrote it right, but in the DB nothing happens, and there is nothing happening on the website too here is my models.py class Department(models.Model): id = models.AutoField(primary_key=True) department = models.CharField(max_length=60) info_grafana = models.TextField() users = models.ManyToManyField(User) and my views.py class ViewUserAccount(View): def post(self, request, id_account: int, *args, **kwargs): if request.POST.get('_method') == 'delete': self.delete(request, id_account) else: self.create(request, id_account) return redirect(request.META.get('HTTP_REFERER')) def delete(self, request, id_account): id_direction = request.POST.get('direction_id') id_project = request.POST.get('project_id') if id_project: project = Project.objects.get(id=id_project) project.users.remove(User.objects.get(id=id_account)) elif id_direction: direction = Department.objects.get(id=id_direction) direction.users.remove(User.objects.get(id=id_account)) the main point that i want to delete user from department/project, but nothing is happening :( -
Trying to hide django secret key, but getting error when deploying in PythonAnywhere
I'm trying to deploy a django project. I hid the secret key putting it in a file called .env and added it to .gitignore, so I have django's secret key only locally, and not in the git repository. But when I try to deploy the project in PythonAnywhere, an error occurs because there is no secret key in the repository (there is no file from where the server could read the secret key). So I understand that it's not good to hard code the key, but how would I do to get a secret key for deployment? I shouldn't have any secret key in the git repository, right? -
two button in a form to display a dictionary is not working
I want to use two buttons in a template form and run two action in a function. when I omit if with only a button, django runs , but when I add if in the codes to execute 2 action , it stops working in view: def result(request): num1 = int(request.GET["num1"]) num2 = int(request.GET["num2"]) if 'add' in request.POST: res = num1 + num2 if 'sub' in request.POST: res = num1 - num2 return render(request, 'home/result.html', {'result': res}) in template named clt <form action="result" > Enter 1st number : <input type="text" name="num1"><br> Enter 2st number : <input type="text" name="num2"><br> <button type="submit" name="subscribe">Subscribe</button> <button type="submit" name="unsubscribe">Unsubscribe</button> </form> in template named result result : {{ result }} -
Trying to Upload database file using python requests and sending to django API
Hi I have a database file. I want to send this database file via python requests post method to my django server and store this database file somewhere in my server. I have following code to send the database file: database = {'uploaded_file': open('<my_local_path>/Old_DB.sqlite3', 'rb')} response = requests.post('http:192.168.20.4/api/app/receive-database', data=database) print(response.status_code) On my API: class DatabaseReceive(views.APIView): permission_classes = (permissions.AllowAny,) def post(self, request): database = request.data data = database.get('uploaded_file') try: newDB = open('<path_to_store_the_database>/New_DB.sqlite3', 'wb') newDB.write(data) result = "Sucess" except Exception as e: result = e return Response(status=status.HTTP_200_OK, data=result) So, basically I am sending the database as a binary file to my api. On my api, I am creating another binary file and trying to write the binary contents from database to my to this new binary file making it a new database. Here I can see that 'data' is a binary contents, but I'm not being able to write this 'data' to my newDB binary file. -
How add user to a group when update and create a user
I created a bunch of groups fallowing this link: https://stackoverflow.com/questions/22250352/programmatically-create-a-django-group-with-permissions#:~:text I subscribed the User class adding a choice field called "role". Basically, that means what role that user has. That way if a user has the role of "staff" . Thus It'll have permissions of the group staff. The problem is: I can't get django to respond the way I expected. I put a signal after saving that it should add the user to the group according to their role. The program looks like this: # project/app/model.py class User(AbstractUser): class Roles(models.IntegerChoices): SUPER = 0, _('SuperAdmins') COMPANY = 1, _('Company') UNITY = 2, _('Unity') STAFF = 3, _('Staff') role: Roles = models.IntegerField(choices=Roles.choices, default=Roles.STAFF, verbose_name=_("Role")) My signal is like: GROUPS = ['SuperAdmins', 'Company', 'Unity', 'Staff'] @receiver(post_save, sender=User) def user(sender: User, instance: User, created: bool, **kwargs) -> None: """ This receiver function will set every staff pages that is created to the group staff. :param sender: the model that will trigger this receiver :param instance: the instance :param created: if it was already created :param kwargs: :return: None """ if created: group = Group.objects.get(name=GROUPS[instance.role]) instance.groups.add(group) else: group = Group.objects.get(name=GROUPS[instance.role]) instance.groups.add(group) print("update") When I go to the admin page and I create a new … -
Django MySQL Access denied for user 'user_name'@'localhost' to database 'db_name'
I'm brand new to Django (1st day) and setting up and environment on a MAC. I'm inside the environment created by pipenv and trying to execute python3 manage.py migrate. I get the error "Access denied for user 'user_name'@'localhost' to database 'db_name'". I have no problems connecting to the database either inside or outside the pipenv environment using the mysql command line tool. MAC version 12.3.1 MySQL version = 8.0.28 Python version = 3.9.12 Ideas? TIA... -
How Do You Properly Copy ManyToMany Fields From One Model To Another
I am trying to override the SAVE of one model and copy specific fields to another model. I swear I had this working....but now it's not. Anyway...Here's an example of what I thought used to work.... def save(self, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) NewModel = Target.objects.create( field=self.field ) NewModel.m2mfield.add(*self.m2mfield.all()) I swear this use to work but now when it gets executed...the "normal" fields copy as expected but the M2M is blank. I've confirmed that the model shows the values in the M2M field....but for whatever reason they aren't being copied over to the "Target" model. Thanks in advance for any thoughts on what I might be doing wrong or what may have chnanged. -
Django multiple distinct values queryset for SQLDB
I'm trying to get a list of results that have distinct x and y values, but I also want to return color along with them. Since I'm using an SQLDB I'm not allowed to use the fieldnames arg of distinct. Is there a good work around for this? All the examples I'm been looking up haven't been working out. The query that I'm not allowed to run: queryset = Tile.objects.values('x', 'y', 'color').distinct('x', 'y')