Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: is there a way to add users to a ManyToManyField of a model each for a certain amount of time?
i have a website that has video courses for my students that they can buy and use, title = ,,, price = ,,, buyer = models.ManyToManyField(User, blank=True, related_name='my_attendance_courses') i want this field to also have expiration date for each user it holds, so my students only have the course for 1 month after they bought it is there a way i can to this? -
Cloud build error: failed to build: executing lifecycle. This may be the result of using an untrusted builder: failed with status code: 51
I am trying to deploy a template Django project to cloud run using cloud shell from the following tutorial: https://codelabs.developers.google.com/codelabs/cloud-run-django In step 7, on running the command: gcloud builds submit --pack image=gcr.io/${PROJECT_ID}/myimage to build the application image, this error is coming: `ERROR: failed to build: exit status 1 ERROR: failed to build: executing lifecycle. This may be the result of using an untrusted builder: failed with status code: 51 ERROR ERROR: build step 0 "gcr.io/k8s-skaffold/pack" failed: step exited with non-zero status: 1 BUILD FAILURE: Build step failure: build step 0 "gcr.io/k8s-skaffold/pack" failed: step exited with non-zero status: 1 ERROR: (gcloud.builds.submit) build 75a52dae-9a4f-4591-af13-5fe1228533b4 completed with status "FAILURE"` The file migration.yaml is same as the tutorial and I have followed all steps exactly as they were in the tutorial. Can someone please help me with this error ? -
Extanding the User model
I am trying to build my first Django backend project, so i'm trying to creatre a REST API end-point that gets a user registration data in json file from the front-end and save it on the database if it's valid. I am trying to save the additional user information in a new model called Player and link it to the default User model using one-to-one-field. When i recive the json file with the data from the front-end the a new user with the data is created in the User model, also a new row is created in the Player model that connected to the user we just created in the User model. But the problem is the fields "height" and "handicap" remain empty. I don't know how to save the "height" and "handicap" parameters into the new Player instance. This is my models.py file: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save from datetime import * # This model extend the basic built-in User model, by adding additional information on the uesr like # handicap score anf height. class Player(models.Model): def __str__(self): return self.user.username user = models.OneToOneField(User, … -
Tried databse queryset on crontab but it doesn't work
Crontab works fine on simple task. e.g def test(): test.objects.create.(name='Dino') but when i tried to query my db it does nothing see example: def test_task(request): if Users_Machine.objects.filter(user=request.user).exists(): test.objects.create(name='Dino', user=request.user) The Users_machine object is present in the db. Here is my models class test(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) Please how can i make this work? -
How to access directory file outside django project
I'm trying to import files that are outside my Django folder, but I get the following error: No module named 'manage_db' It's important to note that I created this package on my local computer, so I don't need to do a pip install. The path from which I want to make a call to the file is: api-yahoo-finance/yahoo/api_yahoo/views I want to import on the following form from the following path: from manage_db.exc_get_symbol import get_symbol And I want to import all the files on the package into the following folder: whose path is manage_db and is outside the api-yahoo-finance folder (On manage_db existing all the files that I want to import) Note: I work with Django Framework. -
Django-wiki installed but root article throws global flag error
I have installed Django-wiki in a fresh virtual Django install. My initial page comes up, the site allows for user registration. Everything looks well until I enter my first Root article. I have kept it rudimentary with a title "Test" and the body just a simple "Hello" but when I save I get this error: error at / global flags not at the start of the expression at position 9 Request Method: GET Request URL: http://aassch1at01.preprod.des:8000/ Django Version: 4.0.8 Exception Type: error Exception Value: global flags not at the start of the expression at position 9 Exception Location: C:\python\Lib\re_parser.py, line 841, in _parse Python Executable: C:\daas_django_apps\env\Scripts\python.exe Python Version: 3.11.0 Error during template rendering In template C:\daas_django_apps\env\Lib\site-packages\wiki\templates\wiki\view.html, error at line 7 Line 7 is: {% wiki_render article %} I have tried checking all my configuration and it seems ok and matches Django-Wiki installation example. Tried changing user ownership of the article and creating a group for viewing but to no avail. Any help would be appreciated. Thank you! -
Filter only one row per one date for different priority
From query which returns multiple rows with different data priority. I need to create subtable with only one date with highest priority. My approach was to just do multiple queries and return query.first(). But this will fire database connection x times, where x is number of different days. list_of_queries = [] for date in dates list: list_of_queries.append( self.get_queryset().filter(date).order_by( Case( *[When(priority__iexact=priority, then=Value(i)) for i, priority in enumerate(priority_list)], default=None ).asc())) Table 1. | ID | DATE | PRIORITY | |---- |------| -----| | 1 | 2022/11/1 | 1 | | 2 | 2022/11/1 | 2 | | 3 | 2022/11/1 | 3 | | 4 | 2022/11/2 | 2 | | 5 | 2022/11/3 | 1 | | 6 | 2022/11/3 | 3 | Table 2. | ID | DATE | PRIORITY | |---- |------| -----| | 1 | 2022/11/1 | 1 | | 4 | 2022/11/2 | 2 | | 5 | 2022/11/3 | 1 | I think I could use some other approach and just gather all rows with date__lte to date__gte and from this subquery in some way just take only one date. But any idea how to do this in Django ORM? Or I have to do multiple … -
How do I find and alter my PATH variable on macOS?
I was forced to reinstall Python and Django after updating to Ventura 13.0.1. However, the Python executables are now in /Users/user/Library/Python/3.9/bin, while the command 'env' shows the PATH variable set to a totally different path. To change this, I need to know the location of my PATH variable, so that I can reference that in my $ echo export PATH="<PATH_TO_PYTHON>:$PATH" >> ~/.profile command in order to alter it, as described here, with ~/.profile being the name of the file containing the PATH variable. However, "ls -la" does not show a .profile, .login, .zsh_profile, .zshrc, or any of the other potential files for this variable. While I tried creating a .zsh_profile file and adding export PATH=$PATH:/Users/user/Library/Python/3.9/bin to it, the command 'env' still shows PATH set to the original file path/directory. Is there a specific command I can use to find the location of that PATH variable, like what file it is being stored in? -
Django + psycopg2 OperationalError could not open certificate file "/root/.postgresql/postgresql.crt": Permission denied
I have a server with ubuntu 22 and a postgres database on digitalocean. I'm deploying a django application there using docker swarm and when I try to access the /admin page I get this error: connection to server at "xxxx.db.ondigitalocean.com" (xx.xxx.xxx.xx), port 25060 failed: could not open certificate file "/root/.postgresql/postgresql.crt": Permission denied I will add that when I created a test script to connect to the database for tests on the server, everything works fine, and I can connect to the database from the local computer. The same project when I run locally connects to the database without any problems DB settings DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "dbname", "USER": "user", "PASSWORD": "pass", "HOST": "xxxx.db.ondigitalocean.com", "PORT": "25060", } } DOCKERFILE FROM python:3.11 ARG GIT_ACCESS_TOKEN RUN git config --global url."https://${GIT_ACCESS_TOKEN}@github.com".insteadOf "ssh://git@github.com" WORKDIR /backend ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY requirements.txt . COPY entrypoint.sh . COPY entrypoint-celery.sh . # ADD /backend /backend COPY /backend /backend RUN python -m pip install -r requirements.txt RUN mkdir -p /backend/tmp RUN chmod -R 777 /backend/tmp RUN mkdir -p /orders/xmls RUN chmod -R 777 /orders/xmls -
Deploying Django app to Remote Red Hat 8 Server. manage.py not working. What am I doing wrong?
I am a 1st year CS Graduate Student who has been put in charge of a refactoring project. The refactoring project has a Django backend that implements a postgresql database using python 3.8. I've never used Django previous to this project so I apologize if the answer is simple. I have the backend refactored and I can run our Django backend locally. However, when I try to run our backend with sudo python3.8 manage.py runserver on our new RHEL 8 server it seems to get hung up after the system check: runserver example I also know that I need to create a super user for the Django postgresql database, but when I run sudo python3.8 manage.py createsuperuser --username <username> Where <username> is an actual name, it also seems to get hung up without outputting anything. Neither of these are outputting an error so I'm unsure what's happening. I know that it's not common practice to use sudo with these commands, but the server gives me permission denied errors if I don't use sudo. I'm not the one who set up the server, our IT department did it and I'm unsure if I needed them to do something specific or not. … -
daisychaining select_related functions?
I have the below which joins the notifications model to the task model and returns all fields - it works! notificationsx = notifications.objects.filter(orgid__in=t).select_related('task').all() But, I also need to join the task model to the projects model - so I have all task, notifications and project fields in one output.I tried the below but it didn't work daisy chaining all the things together. Can anyone help me please? notificationsx = notifications.objects.filter(orgid__in=t).select_related('task').all().select_related('project').all().order_by('-epoch')[:15] -
Setup django DB to show PRODUCT ->> WEBSITE ->> ITEM DETAILS
I want to be scraping and storing products and display the price which may vary depending on website and item details such as price and shipping might be different. I want to know would this structure work? PRODUCT: foreignkey -> website website: foreignkey -> item details or a different suggestion. Anyone? I havent tried anything yet I was wondering what the thoughts on proper structure would be. -
How can I pass the value of a javascript variable to django?
How can I send the value of "const token" to django? function getToken() { PagSeguroDirectPayment.createCardToken({ cardNumber: '4111111111111111', brand: 'visa', cvv: '123', expirationMonth: '12', expirationYear: '2030', success: function(response) { const token = response.card.token; }, error: function(response) { }, complete: function(response) { } }); } the getToken() function is being executed like this: <form action="{% url 'payments' %}" method="POST" onsubmit="getToken()"> I had tried to pass the Token value to a hidden input, and then I tried to get that value in django as shown below, but the input takes a while to receive the value and is already sent to the other page immediately. That way I would need to make sure that the input has the token value to let it forward to the other page success: function(response) { document.getElementById('cardToken').value = response.card.token; }, -
I tried to make MultilingualModel in Django but the language keeps being by default and won't change
i am trying to make multilingual model in Django. But my code doesn't work, it just ignores my function select_language and selects default_language. I have no idea whats causing the error. Here is my code models.py class MultilingualQuerySet(models.query.QuerySet): selected_language = None def __init__(self, *args, **kwargs): super(MultilingualQuerySet, self).__init__(*args, **kwargs) def select_language(self, lang): self.selected_language = lang return self def iterator(self): result_iter = super(MultilingualQuerySet, self).iterator() for result in result_iter: if hasattr(result, 'select_language'): result.select_language(self.selected_language) yield result def _clone(self, *args, **kwargs): qs = super(MultilingualQuerySet, self)._clone(*args, **kwargs) if hasattr(qs, 'select_language'): qs.select_language(self.selected_language) return qs class MultilingualManager(models.Manager): use_for_related_fields = True selected_language = None def select_language(self, lang): self.selected_language = lang return self def get_query_set(self): qs = MultilingualQuerySet(self.model, using=self._db) return qs.select_language(self.selected_language) class MultilingualModel(models.Model): objects = MultilingualManager() # fallback/default language code default_language = None # currently selected language selected_language = None class Meta: abstract = True def select_language(self, lang): """Select a language""" self.selected_language = lang return self def __getattribute__(self, name): def get(x): return super(MultilingualModel, self).__getattribute__(x) try: # Try to get the original field, if exists value = get(name) # If we can select language on the field as well, do it if isinstance(value, MultilingualModel): value.select_language(get('selected_language')) return value except AttributeError as e: # Try the translated variant, falling back to default if … -
Django channels AnnonymousUser on the Safari webbrowser
I have chat where after login you can send message but if you aren't logged user you can't send it, because you are AnnonymousUser and consumer can't take your name. On the Safari browser after login i'm going to 127.0.0.1:3000/chat and i get logged out automatically, but if i'm making it with opened developer tools then i'm still logged and i can send a message. On the other browser (firefox) all work fine. I have no idea. Thanks for your help class ChatRoomConsumer(WebsocketConsumer): def connect(self): self.user = self.scope["user"] self.to_user = 'testowy' async_to_sync(self.channel_layer.group_add)(self.to_user, self.channel_name) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.to_user, self.channel_name ) def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] now = timezone.now() async_to_sync(self.channel_layer.group_send)( self.to_user, { "type": "chat_message", "message": message, "user": self.user.email, "datetime": now.isoformat(), } ) def chat_message(self, event): self.send(text_data=json.dumps(event)) export const Chat = () => { const [messages, setMessages] = useState([]) const [client, setClient] = useState({}) useEffect(()=> { const token = sessionStorage.getItem('access_token') const client = new W3CWebSocket('ws://127.0.0.1:8000/ws/chat/?token=' + token) setClient(client) },[]) client.onmessage = (event) => { const data = JSON.parse(event.data) const fullMessage = { "message": data.message, "datetime": data.datetime, "user": data.user } setMessages((prevState) => [...prevState, fullMessage]) } let corpusMessages if(messages.length > 0){ corpusMessages = ( <Grid> {messages.map((fullMessage)=>{ return ( … -
Deploying Django app with GoDaddy domains and cPanel
I am trying to deploy my first Django app. I already own the domain using goDaddy domains and I am trying to set up the Django application. I am trying to find the terminal in the Advanced section in cPanel but it is not there. how can I use the terminal? -
how can i enable login with email and phone number in Django rest framework?
I want to enable login with an email and phone no in the Django project. Like users can put their email or phone number in the input field as their wish. -
Django .How to show recommended products and products of the same collection in the product card under the product
Each product has a page with a card, more detailed information about the product.How to implement the output on the product card page of all products of the same model. Let's say the Adidas product and below are all Addidas products.The problem is that the product card page displays only information about one product watch_card = get_object_or_404(Whatches, pk=watch_pk) models.py class Collections_foreignkey(models.Model): name=models.CharField(max_length=250, verbose_name='Коллекция') def __str__(self): return self.name ``` class Whatches(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=250, verbose_name='Название') description=models.TextField(verbose_name='Описание',blank=True) collections=models.ForeignKey(Collections_foreignkey, on_delete=models.CASCADE, verbose_name='Коллекция' ,blank=True,null=True,related_name='watches_collections') def __str__(self): return self.title # views.py def watch_card(request, watch_pk): watch_card = get_object_or_404(Whatches, pk=watch_pk) return render( request, 'mains/about/catalog/watches/watch_card.html', context={ 'watch_card': watch_card, }, ) def watches(request): watch_card = Whatches.objects.all() whatches_filter =WhatchesFilter(request.GET,queryset=watch_card) #фильтрация на сайте return render(request,'mains/about/catalog/watches/index.html', context={ 'watch_card': watch_card, 'form':whatches_filter.form, 'whatches_filter':whatches_filter.qs, #фильтр для всего в виде select option из filters.py }, ) -
Showing duplicate data after the data is changed and refresh the page in django python
I want to show the data on localhost only for once as it comes twice and wherever I change the data.py and refresh the page then the new layer of data is adding. So if data is titles = { "data": [ { "sid": "1234", "name": "name_1" }, { "sid": "5678", "name": "name_2" }, { "sid": "9012", "name": "name_3" } ] } then it should appear in the output as SD Name 1234 name_1 5678 name_2 9012 name_3 so if I change the data in data.py file titles = { "data": [ { "sid": "0000", "name": "name_1" }, { "sid": "12313", "name": "name_2" }, { "sid": "543534", "name": "name_3" } ] } the output should appear like this SD Name 0000 name_1 12313 name_2 543534 name_3 current output is SD Name 1234 name_1 5678 name_2 9012 name_3 0000 name_1 12313 name_2 543534 name_3 the output is adding the previous records. What I want is after refreshing it should appear the current data in data.py file views.py from django.shortcuts import render from .models import Title def get(request): context = {'titles': Title.objects.all()} return render(request, "home.html", context) home.html <!DOCTYPE html> <html lang="en"> <head> <title>TableView - Startup</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link … -
No module named 'globals'
I have a folder that has a Django Framework in it. I try to call files that are outside of this folder but I get the following error: No module named 'globals' This path folder: api_yahoo_finance/yahoo/api_yahoo/views And in the views file, I try to use the file that exists outside this folder. (Outside of api_yahoo) I tried to read on the internet and understand what the problem is, I saw comments that said to add a init file, I added it but it didn't help. -
Error while working on the site in Django, part 2
This is a continuation of the previous question. When I continued to work on the site and when I wanted to test the site through "python manage.py runserver" in the C:\mysite\site\miniproject directory, the following error pops up: C:\Program Files\Python36\lib\site-packages\django\db\models\base.py:321: RuntimeWarning: Model 'blog.post' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models. new_class._meta.apps.register_model(new_class._meta.app_label, new_class) C:\Program Files\Python36\lib\site-packages\django\db\models\base.py:321: RuntimeWarning: Model 'blog.post' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models. new_class._meta.apps.register_model(new_class._meta.app_label, new_class) Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 423, in check databases=databases, File "C:\Program Files\Python36\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Program Files\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Program Files\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Program Files\Python36\lib\site-packages\django\urls\resolvers.py", line 416, in check for pattern in self.url_patterns: File "C:\Program Files\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = … -
django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am troubleshooting an NGINX/Django/UWSGI application for a customer, that has been broken beyond expectations. I've been debugging code, and re-writing for 30+ hours now and am at another hurdle that I can't seem to get past on my own. [pid: 336873|app: 0|req: 1/1] 198.11.30.68 () {46 vars in 1070 bytes} [Mon Dec 5 10:04:42 2022] GET / => generated 0 bytes in 393 msecs (HTTP/1.1 500) 0 headers in 0 bytes (0 switches on core 0) announcing my loyalty to the Emperor... Traceback (most recent call last): File "/home/django/django_venv/django_site/wsgi.py", line 26, in application get_wsgi_application(); File "/home/django/django_venv/lib64/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application WSGIHandler(); File "/home/django/django_venv/lib64/python3.6/site-packages/django/core/handlers/wsgi.py", line 127, in __init__ self.load_middleware() File "/home/django/django_venv/lib64/python3.6/site-packages/django/core/handlers/base.py", line 40, in load_middleware middleware = import_string(middleware_path) File "/home/django/django_venv/lib64/python3.6/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/django/django_venv/lib64/python3.6/site-packages/django/contrib/auth/middleware.py", line 3, in <module> from django.contrib.auth.backends import RemoteUserBackend File "/home/django/django_venv/lib64/python3.6/site-packages/django/contrib/auth/backends.py", line 2, in <module> from django.contrib.auth.models import Permission File … -
table has found to column named
My issue is that when i submit my registration form to back it up, the page shows an operationalError and doesn't recognise the first item of my model which is the first name. I've tried makeMigrate after all modifications and rewriting all the items to make sure they match. def registration_view(request): if 'email' in request.GET: newUser = User(firstname=request.GET['firstname'], lastname=request.GET['lastname'], country=request.GET['country'], email=request.GET['email'], phone=request.GET['phone'], password=request.GET['password'], gender=request.GET['gender']) newUser.save() return redirect('/signin') else: response = render(request, 'registration.html') return response from django.db import models class User(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=50) country = models.CharField(max_length=50) email = models.EmailField(max_length=50) phone = models.CharField(max_length=30) password = models.CharField(max_length=128) GENDER_CHOICES = ( ('M','Male'), ('F','Female'), ('X','X'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) friends = models.ManyToManyField('self') conjoint = models.OneToOneField('self', on_delete=models.CASCADE) def __str__(self): return self.firstname + ' ' + self.lastname class WallMessage(models.Model): author = models.ForeignKey('User', on_delete=models.CASCADE) content = models.TextField() publication_date = models.DateField() -
django add amp; to context value , how to solve that ,
I pass url from view by context like this : context = {"url":"https://fra1.digitaloceanspaces.com/logatta-space/organization_survey/static/img/page1-d.jpg?AWSAccessKeyId=DO00GN8LVUJB9VNAQL69&Signature=EM6bumz7gPzaPBPqHHdGfqBMVWk%3D&Expires=1670256832"} return render(request, 'index1.html', context) when i recive the same url like this from chrome inspect: .start-template { background-image:url(https://fra1.digitaloceanspaces.com/logatta-space/organization_survey/static/img/page1-d.jpg?AWSAccessKeyId=DO00GN8LVUJB9VNAQL69&amp;Signature=EM6bumz7gPzaPBPqHHdGfqBMVWk%3D&amp;Expires=1670256832); } the template add amp; to the url inside the template and this casess some problems and this is my html code : background-image:url({{url}}); my question: how to pass url as is ,without add amp; in middel of my url -
ValueError when i compare input values with database object
I want to compare form input with database value. For example: There's a input field called password .. and i want to compare the input value with a password inside the database (in case i know the row already (id)) But when i compare it, i got valueerror like this. googling like 2 hours and nothing works. I'm new to django .. I hope someone can help me :D Here is my view code id = modelUser.objects.values('id').filter(username=txtUsername) checkPassword = modelUser.objects.values('password').filter(username=txtUsername) if(txtPassword == checkPassword.password): return render(request,'success.html') Models.py class modelUser(models.Model): firstname = models.CharField(max_length=200, null=False, blank=False) lastname = models.CharField(max_length=200, null=False, blank=False) username = models.CharField(max_length=200, null=False, blank=False) password = models.CharField(max_length=200, null=False, blank=False) def __str__(self): return self.username