Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: apply constraint on 'choices'-based property on model
I want to apply a constraint in the following way: Imagine that you have a Charfield property with some choices. class ExampleChoices(models.TextChoices): A = "A", "a" B = "B", "b" C = "C", "c" D = "D", "c" property = models.CharField(choices=ExampleChoices.choices, default=ExampleChoices.A) I now want to put constraints on two of those choices, rules: If choice C is used I want it to be unique and cannot be used anywhere else, with that D cannot be used at all The same rule applies for when D is used, D must be unique and C cannot be used anywhere else. In the previous occasions all other choices can just be used like normally. How would I achieve this? -
celery ModuleNotFoundError: No module named 'django.config'
I'm getting this error after running the command: celery -A slots worker -l DEBUG Trace back Traceback (most recent call last): File "/opt/kff/Whiplash-Server-Env/bin/celery", line 8, in <module> sys.exit(main()) File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/celery/bin/celery.py", line 217, in main return celery(auto_envvar_prefix="CELERY") File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/click/core.py", line 1655, in invoke sub_ctx = cmd.make_context(cmd_name, args, parent=ctx) File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/click/core.py", line 920, in make_context self.parse_args(ctx, args) File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/click/core.py", line 1378, in parse_args value, args = param.handle_parse_result(ctx, opts, args) File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/click/core.py", line 2360, in handle_parse_result value = self.process_value(ctx, value) File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/click/core.py", line 2322, in process_value value = self.callback(ctx, self, value) File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/celery/bin/worker.py", line 160, in <lambda> value: value or ctx.obj.app.conf.worker_state_db, File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/celery/utils/collections.py", line 112, in __getattr__ return self[k] File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/celery/utils/collections.py", line 392, in __getitem__ return getitem(k) File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/celery/utils/collections.py", line 250, in __getitem__ return mapping[_key] File "/usr/lib/python3.8/collections/__init__.py", line 1006, in __getitem__ if key in self.data: File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/kombu/utils/objects.py", line 30, in __get__ return super().__get__(instance, owner) File "/usr/lib/python3.8/functools.py", line 967, in __get__ val = self.func(instance) File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/celery/app/base.py", line 138, in data return self.callback() File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/celery/app/base.py", line 967, in _finalize_pending_conf conf = self._conf = self._load_config() File "/opt/kff/Whiplash-Server-Env/lib/python3.8/site-packages/celery/app/base.py", line 977, in _load_config … -
I'm trying to run a django application, when I do python manage.py runserver, I'm getting the following error
error I get this keyerror:product-promotion error when i try to run this django application with python manage.py runserver. I've gone through the settings.py a dozen times, made sure that the db credentials are correct but i cant figure out what the error is. Im expecting the app to run but instead i see this error in my terminal. Any suggestions in the right direction will help me a lot. -
Django admin got weird when I upgraded to 4.2 [closed]
Django admin on 4.2 I upgraded to django 4.2, and that happened... -
Is there any way to highly compress PDF files through python?
I have generated a PDF file through python using pdfkit library running on django server. The size of pdf generated is 43.2 MB. Total pages in pdf = 15. Each page has 70 images, each image size = 623 bytes. Tech Stack version used- -Python = 3.8.16 -pdfkit = 1.0.0 -wkhtmltopdf = 0.12.6 -Django = 3.2.16 System OS = Ubuntu 22.04.2 LTS Requirement is to compress this pdf file without compromising with the quality of content, images in it. Any approach or suggestions for improvements in **the things tried**? Things tried: PDFNetPython3 python package- requires license/key file. Ghost-script command from system(ubuntu) terminal to reduce file. shrinkpdf.sh - file got from github. ps2pdf command from system terminal. pdfsizeopt cpdf Making zip of original file Changing dpi value in pdfkit options. File size after compression with quality of content maintained = 23.7 MB. Expectation is have more reduction in file size. -
I receive a 502 ( Bad Gateway) error when trying to create campaigns with adsets and ads using the Facebook API
I have a Python Django web application, which has an app inside that is used for creating campaigns with adsets and ads using the facebook_business package. The weird thing is that it works fine from localhost, i can create as many adsets as I want. However when trying it live, it sometimes works, but 70% of the time it does not. I receive a 502 error, however i am 100% sure I am doing something wrong. The way i call it is the following. I make an ajax call to a view in analytics/views.py def create_campaign(request): if request.method == 'POST': campaign_name = request.POST.get('campaign_name') product_id = request.POST.get('product_id') link_url = 'domain_name...' + Product.objects.get(id=product_id).get_absolute_url() print(link_url) adsets = json.loads(request.POST.get('adsets')) campaign = ad_campaigns.create_facebook_campaign(campaign_name=campaign_name) campaign_id = campaign['id'] print(campaign) for adset in adsets: adset_name = adset['adset_name'] budget = int(adset['adset_budget']) min_age = int(adset['adset_minage']) max_age = int(adset['adset_maxage']) audience_id = adset['adset_audience_id'] audience_name = adset['adset_audience_name'] if "genders" in adset: genders = adset['genders'] budget = budget * 100 created_adset = ad_campaigns.create_facebook_adset(campaign_id=campaign_id, name=adset_name, budget=budget, max_age = max_age, min_age = min_age, interest_id=audience_id, interest_name=audience_name) created_adset_id = created_adset['id'] for ad in adset['ads']: ad_image = '' ad_video = '' ad_thumbnail = '' ad_name = ad['ad_name'] ad_primary = ad['ad_primary_text'] ad_headline = ad['ad_headline'] ad_description = ad['ad_description'] ad_type = ad['ad_type'] … -
Serilaizer is creating a new object instead of editing an existing one
I have a serializer like the following : class PutAwayProductsPositionSerializer(serializers.ModelSerializer): class Meta: model = PutAwayProductsPosition fields = "__all__" class PutAwaySerializer(serializers.ModelSerializer): products_position = PutAwayProductsPositionSerializer(many=True) class Meta: model = PutAway fields = "__all__" def create(self, validated_data): items_objects = validated_data.pop('products_position', []) prdcts = [] for item in items_objects: i = PutAwayProductsPosition.objects.create(**item) prdcts.append(i) instance = PutAway.objects.create(**validated_data) print("prdcts", prdcts) instance.products_position.set(prdcts) return instance def update(self, instance, validated_data): items_objects = validated_data.pop('products_position', []) print("items_objects in update", items_objects) prdcts = [] for item in items_objects: kp_instance, created = PutAwayProductsPosition.objects.update_or_create(pk=item.get('id'), defaults=item) prdcts.append(kp_instance.pk) instance.products_position.set(prdcts) instance = super(PutAwaySerializer, self).update(instance, validated_data) return instance When I try to edit a particular object this update_or_create always creates a new entry. I checked for the error by printing the validated data and it seems the serilaizer is not validating the id field despite the serilizer's model being set to "all" How do I solve this ? The data I get from serliazer is the following : { "id": 13, "products_position": [ { "id": 297, "put_position": "F.G.H.I.J", "is_put": true, "products": 312 }, { "id": 298, "put_position": "F.G.H.I.J", "is_put": true, "products": 310 }, { "id": 299, "put_position": "F.G.H.I.J", "is_put": false, "products": 310 }, { "id": 300, "put_position": "F.G.H.I.J", "is_put": false, "products": 310 }, { "id": 301, "put_position": "F.G.H.I.J", … -
How to access functions or models in models.py or views.py from one app to another
i am new to django and working on my first project. i know the way to connect view functions and models etc in a single app. but now as in a bigger project i kind off needed to add more apps in my project. and no i am facing a situation to connect one model (CustomUser) to another app's models.py file. from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): username = models.CharField(max_length=50) email = models.EmailField(unique=True) phone = models.CharField(max_length=10) the code above is my accounts/models.py model class. from django.db import models from accounts.models import CustomUser this is exactly how i tried to access from my registrations/models.py model class. but i can't access it and also not giving any suggestions of that model while i type the model name. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'crispy_bootstrap5', 'django_otp', 'django_otp.plugins.otp_totp', 'accounts', 'admins', 'users', 'registrations', ] from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin-panel/', admin.site.urls), path('', include('users.urls')), path('accounts/', include('accounts.urls')), path('admins/', include('admins.urls')), path('registrations/', include('registrations.urls')), ] these are the settings.py file and main urls.py file. Hope for the solution, Thank you for the consideration.... i researched on lots of documents and it all says to do … -
Why I got error message in the form even if it has a correct info
I have this nitification model class Notification(models.Model): sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='sender') reciever = models.ForeignKey(CustomUser,unique=False, on_delete=models.CASCADE, related_name='reciever') body = models.CharField(max_length=150) blog = models.ForeignKey(Blog, on_delete=models.CASCADE) permissions = models.CharField(max_length=250, null=True) timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def __str__(self): return f'form {self.sender} , to : {self.reciever}' and here is the form class InviteMemberForm(forms.ModelForm): email = forms.EmailField() permissions = forms.MultipleChoiceField( widget=forms.widgets.SelectMultiple(attrs={'class':'form-control mb-2'}), choices=( ('can_create_posts', 'Can create posts'), ('can_delete_posts', 'Can delete posts'), ('can_edit_blog_settings', 'Can change blog name and description'), ('can_invite_members','Can invite members') ), ) class Meta: model = Notification fields = ['email', 'body'] def clean_email(self): email = self.cleaned_data['email'] if CustomUser.objects.filter(email=email).exists(): user = CustomUser.objects.filter(email=email).first() else: raise forms.ValidationError("There is no user with this email") if email == self.instance.email: raise forms.ValidationError("You can't invite yourself to join the blog") if Notification.objects.filter(reciever__email=email).exists(): raise forms.ValidationError('You sent an invitation for this user before') self.cleaned_data['user'] = user # Return the email address from the cleaned data return email def save(self, commit=True): notification = super().save(commit=False) notification.sender.set([self.instance]) notification.reciever = self.cleaned_data['user'] if commit: notification.save() return notification and here is the view too class BlogMembers(FormView): form_class = InviteMemberForm template_name = 'blog_members.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog = Blog.objects.filter(blog_code=self.kwargs.get('blog_code')).first() context['blog'] = blog context['members'] = blog.members.all() return context def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['instance'] = self.request.user return … -
Django / Python calendar module
I want to add a link to a calendar, so every single day will have a link to the day page, as you can see from the urls.py every link is already generate dynamically. When in html you show the HTMLCalendar {{ cal | safe }} you can see the days, but how can i add a link to every single day? I've been trying a for loop with no success for the last two days. Happy to buy a box of beer to anybody who will help me from django.urls import path from dayplanner import views app_name = 'dayplanner' urlpatterns = [ #Day Planner Home Page path('', views.dayplanner, name='dayplanner'), path('<int:year>/<str:month>/<int:day>', views.dayplanner, name='dayplanner'), ] {% extends 'core/base.html' %} {% block content %} <div style="max-width: 500px; margin-left: 20%;"> {{ cal | safe }} </div> {% endblock %} from django.shortcuts import render import calendar from calendar import HTMLCalendar from datetime import datetime from datetime import datetime as date def dayplanner(request, year=datetime.now().year, month=datetime.now().strftime('%B'), day=datetime.now().strftime('%A')): # Capitalize the title month = month.title() # Shows the month number month_number = list(calendar.month_name).index(month) # This is the Calendar object cal = HTMLCalendar().formatmonth(year, month_number) # Generate links to each day in the calendar day_links = '' for day_number … -
Django form does not render properly
I have a Django form that is not rendering properly on the template. The form tag render with an input, but the input renders as hidden with the value as the csrf token. I don't know what I'm doing wrong. I tried with the basic form on the Django documentation and it's the same thing. None of the previous posts have helped My form: class StorySubmitForm(forms.Form): story = forms.CharField(widget=forms.Textarea(attrs={"cols":100,"rows":6}),required=True) My views: def CompletionView(request): template_name = "completion.html" if request.method == 'POST': form = StorySubmitForm(request.POST) if form.is_valid(): story = form.cleaned_data filename = userid['id_field'] + "Results.csv" f = open(filename,"w+") writer = csv.writer(f) writer.writerow(['Role', 'Input', 'Final Story']) for chat in chat_history: writer.writerow([chat['role'], chat['content'] ]) f.close() return redirect("completion") else: form = StorySubmitForm() return render(request, template_name, {'form':form}) My template: <div class="col-sm-4 my-auto justify-content-center"> <div id="storysubmitwindow" style="display:none"> <h6>Please paste your final story here. Submit your story by pressing the "Submit" button</h6> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.story}} <div id="chatwindow-btn"> <button type="submit" class="btn btn-primary" id="submit-btn">Submit</button> </div> </div> Thanks for the help! -
how to order the in depth levels of a response in DRF
[ { "id": 1, "blocks": [ { "id": 1, "qustions": [ { "id": 1, "question": "هل يظهر الطفل انه يريد الانتباه إليه ؟", "score": "0,2" }, { "id": 2, "question": "هل يثرثر الطفل او يصدر اصواتا أخرى قد تعتبر محاولات للحديث ؟", "score": "0,2" } ], "basal_age": 6 }, { "id": 2, "qustions": [], "basal_age": 12 } ], "name": "Social dimension" } ] I want to order the blocks based on the basal_age here is a snippet on my code my models class PortageQuestion(models.Model): question = models.TextField() score = models.CharField(max_length=10) block = models.ForeignKey('PortageBlock', on_delete=models.CASCADE, related_name='qustions') def __str__(self): return self.question class PortageBlock(models.Model): basal_age = models.IntegerField() test = models.ForeignKey('PortageTest', on_delete=models.CASCADE, related_name='blocks') def __str__(self): return str(self.basal_age) class PortageTest(models.Model): name = models.TextField(null=True, blank=True) general_test = models.ForeignKey(GeneralTest, on_delete=models.CASCADE, null=True, related_name='protage_general_test') def __str__(self): return self.name my serializers class GeneralTestSerializer(serializers.ModelSerializer): general_test = TestSerializer(many=True, read_only=True) class Meta: fields = ('__all__') model = models.GeneralTest class PortageQustionSerializer(serializers.ModelSerializer): class Meta: model = models.PortageQuestion exclude = ['block',] class PortageBlockSerializer(serializers.ModelSerializer): qustions = PortageQustionSerializer(many=True, read_only=True) class Meta: model = models.PortageBlock exclude = ['test',] class PortageTestSerializer(serializers.ModelSerializer): blocks = PortageBlockSerializer(many=True, read_only=True) class Meta: model = models.PortageTest exclude = ['general_test',] depth = 1 my view class PortageView(mixins.ListModelMixin, generics.GenericAPIView): serializer_class = serializers.PortageTestSerializer def get_queryset(self): test_type = self.request.headers.get('test-type') general_test … -
DJANGO: ValueError: too many values to unpack (expected 2) when executing makemigrations
I'm getting the error bellow when trying to execute makemigrations on my django app: ERROR Traceback (most recent call last): File "D:\GitHub\Laurant-Bookstore-2\manage.py", line 22, in <module> main() File "D:\GitHub\Laurant-Bookstore-2\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\GitHub\Laurant-Bookstore-2\venv\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\GitHub\Laurant-Bookstore-2\venv\Lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "D:\GitHub\Laurant-Bookstore-2\venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\GitHub\Laurant-Bookstore-2\venv\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "D:\GitHub\Laurant-Bookstore-2\venv\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\GitHub\Laurant-Bookstore-2\app\livraria\models.py", line 40, in <module> class Carrinho(models.Model): File "D:\GitHub\Laurant-Bookstore-2\app\livraria\models.py", line 44, in Carrinho name, path, args, kwargs = super().deconstruct() ^^^^^^^^^^^^^^^^^^^^^ File "D:\GitHub\Laurant-Bookstore-2\venv\Lib\site-packages\django\db\models\fields\related.py", line 679, in deconstruct app_label, model_name = self.remote_field.model.split(".") ^^^^^^^^^^^^^^^^^^^^^ ValueError: too many values to unpack (expected 2) MODELS.PY from django.db import models from django.contrib.auth.models import User class GeneroLiterario(models.Model): nome = models.CharField(max_length=20) def __str__(self) -> str: return self.nome class Autor(models.Model): nome = models.CharField(max_length=30, blank=False, null=False) foto = models.ImageField(upload_to="autores/%d-%b") biografia = models.TextField(max_length=2000, blank=False, … -
How can I display byte encoded PDF in HTML?
My goal is to download a file from a file-sharing application (Egnyte) and render it in my own HTML. I'm working in Django. I'm getting a 200 response from the storage service: response.headers: {'Content-Type': 'application/pdf;charset=UTF-8',...etc} response.content: first 100 char. Type <Class Bytes>. b'%PDF-1.6\r%\xe2\xe3\xcf\xd3\r\n12090 0 obj\r<</Filter/FlateDecode/First 2063/Length 4726/N 197/Type/ObjStm>>stream\r\n' However, when I pass the response.content to the template.html as the source for an embed, the page is blank. What am I missing? I've tried using different html containers. I don't get any errors but in all cases the element is just blank. <iframe src="b'%PDF-1.6\r%\xe2\xe3\...etc'"> -
Spotipy token doesnt change with each new authorisation
I have been trying to fix this all day. Basically after setting this authentication flow up i logged in with my spotify account that is also my dashboard account (idk if that makes any difference). Everything worked how i wanted and i could display my top songs and artists. However when i change the spotify user/log into a different spotify account, the infromation doesnt update. Instead it keeps displaying infromation from the first spotify login. Every time the authorisation happens the token seems to remain the same, even though it shouldnt? (I think). sp_oauth = spotipy.oauth2.SpotifyOAuth( client_id='client_id', client_secret='client_secret', redirect_uri='http://localhost:8000/accounts/spotifyStats/callback/', scope=['user-read-email','user-read-private','user-top-read'], show_dialog=True) def spotify_authorize(request): if request.user.is_authenticated: # Create a new SpotifyOAuth object auth_url = sp_oauth.get_authorize_url() return redirect(auth_url) else: return redirect('accounts:signin') def spotify_callback(request): code = request.GET.get('code') token_info = sp_oauth.get_access_token(code) print(token_info['access_token']) request.session['access_token'] = token_info['access_token'] return redirect('accounts:spotifyStats') def spotify_stats(request): access_token = request.session.get('access_token') if not access_token: return redirect('accounts:spotify_authorize') sp = spotipy.Spotify(auth=access_token) userartists = sp.current_user_top_artists(time_range='long_term') usertracks = sp.current_user_top_tracks(time_range='long_term') return render(request, 'spotify_stats.html', {'artists': userartists, 'tracks': usertracks}) I want to display information related to every account that logsin/authorises into my website and im not sure how to do it. -
404 when I use traefik and nginx with django
I try to deploy a django-webapp on an ec2-instance. The project was generated with cookiecutter-django. However i want to host my personal website on the same instance, so I changed the corresponding compose-files traefik-compose services: traefik: image: traefik:latest restart: unless-stopped command: # Experimentell, um das Dashboard ohne Zugriffsschutz aufzurufen #- "--api.insecure=true" - "--providers.docker" - "--providers.docker.exposedByDefault=false" - "--providers.docker.network=traefik_web" - "--entrypoints.http.address=:80" - "--entrypoints.http.http.redirections.entrypoint.to=https" - "--entrypoints.http.http.redirections.entrypoint.scheme=https" - "--entrypoints.https.address=:443" # Vermeidet, dass wir den resolver in jedem container mit "traefik.http.routers.https.tls.certresolver=le" angeben muessen - "--entrypoints.https.http.tls.certResolver=le" - "--certificatesresolvers.le.acme.tlschallenge=true" - "--certificatesresolvers.le.acme.email=myemail@gmail.com" - "--certificatesresolvers.le.acme.storage=/letsencrypt/acme.json" ports: - "80:80" - "443:443" - "8080:8080" volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - ./letsencrypt:/letsencrypt networks: - public networks: public: name: public personal website compose works just fine services: nginx: image: nginx:latest restart: unless-stopped container_name: "personal_website" volumes: - ./src:/usr/share/nginx/html labels: - "traefik.enable=true" - "traefik.http.routers.nginx.rule=Host(`domain.net`)" networks: - public networks: public: external: true the django compose version: '3' networks: public: external: true db: volumes: production_postgres_data: {} production_postgres_data_backups: {} production_traefik: {} services: django: &django build: context: . dockerfile: ./compose/production/django/Dockerfile image: sommelier_production_django depends_on: - postgres - redis env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start networks: - public - db labels: - "traefik.enable=true" - "traefik.http.routers.sommelier.rule=Host('sub.domain.net')" - "traefik.http.services.sommelier.loadbalancer.server.port=5000" - "traefik.http.routers.sommelier.entrypoints=websecure" - "traefik.http.routers.sommelier.tls.certresolver=myresolver" - "traefik.docker.network=public" - "traefik.http.middleware.sommelier.headers.hostproxyheaders=X-CRSFToken" redis: image: redis:6 networks: - db postgres: … -
Timestamp updating value over every item in a list rather than each one individually
New to Django here, I have two Django classes representing two different lists: models.py class Playinglist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() started_on = models.DateTimeField(auto_now=True) class Playedlist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() finished_on = models.DateTimeField(auto_now=True) And two functions that add data from one list to another: views.py def add_to_playinglist(request, game_id): obj = Playinglist.objects.filter(game_id=game_id, user=request.user.username) if obj: obj.delete() game = Game.objects.get(id=game_id) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") else: obj = Playinglist() obj.user = request.user.username obj.game_id = game_id obj.save() game = Game.objects.get(id=game_id) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") def add_to_playedlist(request, game_id): obj = Playedlist.objects.filter(game_id=game_id, user=request.user.username) if obj: obj.delete() game = Playinglist.objects.get(game_id=game_id) played_game = Playedlist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") else: obj = Playedlist() obj.user = request.user.username obj.game_id = game_id obj.save() game = Playinglist.objects.get(game_id=game_id) game.delete() played_game = Playedlist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") And to organize/display that data I am using this function: def profile(request): playinglist = Playinglist.objects.filter(user=request.user.username) playinglist_items = [] playing = 0 present_in_playinglist = False if playinglist: for item in playinglist: try: game = Game.objects.get(id=item.game_id) playinglist_items.append(game) present_in_playinglist = True playing += 1 playinglist = Playinglist.objects.get(id=item.game_id) except: present_in_playinglist = False playedlist = Playedlist.objects.filter(user=request.user.username) playedlist_items = [] finished = 0 present_in_playedlist = False if playedlist: for item in playedlist: try: … -
django chained manytomany field filter
class Question(models.Model): subject = models.ForeignKey(Subject, on_delete=models.PROTECT) topic = ChainedForeignKey(Topic, on_delete=models.PROTECT) question = models.TextField(max_length=700, null=False) option_A = models.CharField(max_length=150) option_B = models.CharField(max_length=150) option_C = models.CharField(max_length=150) option_D = models.CharField(max_length=150) correct_option = models.CharField(max_length=150) explaination = models.TextField(max_length=500, null=True ,blank=True) def save(self, *args, **kwargs): # Ensure only one correct option is selected correct_options = [o for o in [self.option_A, self.option_B, self.option_C, self.option_D] if o == self.correct_option] if len(correct_options) != 1: raise ValueError('Exactly one option must be selected as correct') super().save(*args, **kwargs) def __str__(self): return "%s %s %s" % (self.question[:100], self.topic, self.subject) class Quiz(models.Model): name = models.CharField(max_length=255) description = models.TextField(max_length=500, blank=True) subject = models.ManyToManyField(Subject, null=True, blank=True) topics = models.ManyToManyField(Topic, null=True,) questions = models.ManyToManyField(Question) def save(self, *args, **kwargs): super().save(*args, **kwargs) self.questions.set(Question.objects.filter(topics__in=self.topics.all())) def __str__(self): return self.name i want to create view to generate quiz. when user select subjects(2-3)then only related topic (to subject) should appear in topic list. after selectin topic (3-4) only question related to selected topic should appear. if its possible in django-admin that would be more continent -
Django Model - Auto Referencing
class BusinessUnit(models.Model): class Meta: db_table = 'carecode_business_unit' parent_business_unit = models.ForeignKey(BusinessUnit) "BusinessUnit" is not defined. Is it possible to create an auto-referencing model in Django? -
Celery, ModuleNotFoundError
After command 'celery -A store worker -l INFO' (store is a name of project), i`ve error ModuleNotFoundError: No module named 'proj.settings' -----------------------------------------------------------------------------------------------------------. -
How to use a field in django template from a object of foreignkey model
models.py class Position(models.Model): positions = models.CharField(max_length = 200) pub_date = models.DateTimeField('date published') def __str__(self): return self.positions class Candidate(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField('User Email') mobile_no = models.CharField(max_length=10) candidate_image = models.ImageField(null=False, blank=False, upload_to="candidate_images/") description = models.TextField(null=True, blank=True) votes = models.IntegerField(default = 0) positionc = models.ForeignKey(Position, on_delete = models.CASCADE, related_name ='candidateobj') def __str__(self): return self.first_name views.py def candidate_list(request): candidate_list = Candidate.objects.get(pk=1) return render(request, 'candidate_list.html', { "candidate_list": candidate_list, }) candidate_list.html <div class="card-header"> {{ candidate_list.position.positions }} </div> Here I should get to see the position from the 'Position' model. But nothing is rendering for the above code. Other information are showing properly in candidate_list.html. I checked google and found article also . The Stackoverflow solution is the exact issue I believe and I did the similar in my code but didn't get anything in the html page. I'm new in django. -
CSS Background Image not displaying within Django framework
Following the Polls Webapp tutorial in Django. Keep receiving a 404 error through my command line and my image icon is displayed, but not the image itself. Tried changing the path a couple times, resetting the static migration, and changing my static root. Still no image. Here is my style.css li a { color: green; } body { background-image: url('static/images/background.png') no-repeat; } Here is my index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a> </li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} {% load static %} <link rel="stylesheet" href="{% static 'polls/style.css' %}"> <img src="{% static 'static/images/background.png' %}" alt="My Image"> Here is some of my settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Anyone have an idea? -
Heroku deployment not picking up latest commits when building Django app (e.g. recent changes to settings.py )
I'm using git trying to deploy to a staging pipeline on Heroku. My build is failing. Based on the traceback (two of them, below), I have a general sense as to why. It involves my dynamic SECRET_KEY configuration variable in settings.py. The traceback refers to a python-decouple module installed previously. So I commented out the import line to that package in settings.py, removed the package from my requirements.txt, and used this instead: from dotenv import load_dotenv load_dotenv() ... SECRET_KEY = str(os.getenv('SECRET_KEY')) That's the latest version. When I save my changes, commit them, and then push to the staging pipeline, the traceback being returned refers to line 27 as if is still like this: from decouple import config ... SECRET_KEY = config('SECRET_KEY') I’m not sure why Heroku is not picking up the latest and most recent changes. Any ideas? Here is my full build traceback: $ git push staging main Enumerating objects: 4016, done. Counting objects: 100% (4016/4016), done. Delta compression using up to 20 threads Compressing objects: 100% (3932/3932), done. Writing objects: 100% (3965/3965), 6.41 MiB | 3.71 MiB/s, done. Total 3965 (delta 302), reused 0 (delta 0), pack-reused 0 remote: Resolving deltas: 100% (302/302), completed with 15 local objects. … -
Conversation handler not advancing to next state on Heroku correctly
I've developed a webhook-type Telegram bot that is integrated into a Django application using the python-telegram-bot(v13.15) library. Locally, the conversation handler works correctly, but after deploying the application to Heroku, it sometimes fails to advance to the next state in the conversation. Instead, it treats incoming messages as if they are part of the echo handler, and only advances to the next state after the user sends the message again. I've checked that everything is set up correctly on Heroku and there are no delays between messages, so I'm not sure what could be causing the problem. This is what working with the bot looks like using the Heroku version: Example of conversation handler using Heroku This is what working with the bot using the local version looks like: Example of conversation handler locally Here's the relevant code: import json from django.http import HttpResponse, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt from telegram_bot.buttons import * from telegram_bot.handlers.cart_handler import * from telegram_bot.handlers.checkout_handler import * from telegram_bot.handlers.delivery_handler import * from telegram_bot.handlers.order_handler import * from telegram_bot.handlers.payment_handler import * from telegram_bot.handlers.product_handler import * from telegram_bot.utils import * @debug_requests def start_handler(update: Update, context: CallbackContext): context.bot.send_message( chat_id=update.effective_chat.id, text="Hello! I'm a bot. What can I do for you?", reply_markup=get_base_reply_keyboard() … -
VISIT LINK is not working in Django Framework and Cannot see the homepage
I have a project presentation on Monday, and the project topic is SPORTS CLUB MANAGEMENT which is based on Django REST API Framework. And I have a basic understanding of Django. My Problems: When I visited http://127.0.0.1:8000/, I couldn't find the admin_home or homepage of the main website. I tried to read this doc and did plenty of changes but can't get it to work :( Here's the problem demo: Some Errors I got while doing this: Traceback Error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.7 Python Version: 3.10.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'scmapp'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\win10\PycharmProjects\sportsClubManagement-django\templates\admin_login.html, error at line 39 'scmapp' is not a registered namespace 29 : 30 : <div class="container-fluid"> 31 : <div class="row justify-content-center"> 32 : <div class="col-lg-6 loginBox"> 33 : Login<br> 34 : <span style="font-size:18px;">{{ status }}</span> 35 : 36 : <div class="row justify-content-center"> 37 : <div class="col-lg-6"> 38 : <div class="inputBox" style="font-size:18px;"> 39 : <form action=" {% url 'scmapp:login_admin' %} " method="post"> 40 : {% csrf_token %} 41 : Username<br> 42 : <input type="text" name="name" autocomplete="off" required> 43 : 44 : Password<br> 45 : <input type="password" …