Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: return value and not key when serialize a foreign field in DRF
I'd like to ask how I can get the ForeignKey (or ManyToMany) text value to show up in a GET request. Below will produce a JSON with keys referring to either choices or ForeignKey [ { "album_name": "Album_1", "grade": "1", "artist": 2 } ] but I'd like it to display [ { "album_name": "Album_name_NN", "grade": "Bad", "artist": "Artist_name_NN" } ] Those examples I find related to ForeignKey, either on Django Rest Framworks own site or at SO or through various blog posts are not very clear cut and tend to complicate an explanation/solution by also using indirect relationships, as such example is given on the DRF site. At least I cannot implement them into below. I am looking for a minimum viable solution for values to come up in a GET request given below setup. ## Models.py class Artist(models.Model): artist_name = models.CharField(max_length=100) comment = models.CharField(max_length=100) def __str__(self): return (self.artist_name) class Album(models.Model): GRADE = ( ("1", "Bad"), ("2", "Average"), ("3", "Good"), ) album_name = models.CharField(max_length=100) grade = models.CharField(max_length=100, choices=GRADE) artist = models.ForeignKey(Artist, blank=True, on_delete=models.CASCADE) def __str__(self): return (self.album_name) ## views.py class AlbumViewSet(viewsets.ModelViewSet): queryset = Album.objects.all() serializer_class = AlbumSerializer ## Serializers.py class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album fields = ['album_name', 'grade', … -
django DateField is charfield
I'm using django.forms ModelForm. I have DoB which is 'datefield', however, when I display the form the DoB it is displaying like charfield. What should I do so the user be able to select date? Any help is appreciated. Thank you model: dob = models.DateField(validators=[MinValueValidator(18), MaxValueValidator(70)],blank=True, null = True, verbose_name="Day of birth") HTML: <form method = 'POST' > {{ edit_profile | crispy}} {% csrf_token %} <button type = 'submit' name = 'submit' class = 'btn-edit'>Save</button> </form> -
Celery not taking advantage of all CPUs
We have recently moved a monolith app into a microservice architure. We have 10 different micro services using AWS Beanstalk, Aurora serverless, SQS queues and Elastic Cache Redis. We communicate between services with queues, and we send everything to celery on each microservice, so that all request can be handled multi threading. The main problem that we have is that celery is not taking 100% of the cpu resources, we tried to move from 2cpu to 4cpu and now to 8cpu and each cpu never goes over 20%. I using python and django. The way I create the celery services in AWS beanstalk is as follows: On postdeploy hooks, we create 3 different services with 3 different queues, high priority, default and low priority: Default: #!/usr/bin/env bash # Create the celery systemd service echo "[Unit] Description=Celery service for My App After=network.target [Service] Type=simple Restart=always RestartSec=10 User=root WorkingDirectory=/var/app/current ExecStart=$PYTHONPATH/celery -A saul worker -l INFO -Q default,celery,saul --autoscale 4,2 -n worker@%%h -f /var/log/celery.log EnvironmentFile=/opt/elasticbeanstalk/deployment/env [Install] WantedBy=multi-user.target " | tee /etc/systemd/system/celery.service # Start celery service systemctl start celery.service # Enable celery service to load on system start systemctl enable celery.service High Priority: #!/usr/bin/env bash # Create the celery systemd service echo "[Unit] Description=Celery … -
Can i use Django urls and Vue routes in the same project?
I added VueJS to my Django app using django webpack loader, but now i don't understand how to handle routes in my project. I already built the authentication part of my app using Django templates, but since now i added Vue, does it mean that i have to remake authentication in Vue? Or is it possible to keep the authentication page rendered by a django template and using my urls.py and then, once the user is logged in, the routes are handled by Vue (so it becomes a SPA)? So basically i have: from django.urls import path, include from . import views from .views import SignUpView urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), path('login/', LoginView.as_view(), name='login'), ... path('', views.index, name='index') ] So after logging in, the other urls should be handled by a Vue router (that i still haven't created). What happens if i do this? If the route is handled by Vue, will the user still be logged and can i still use logout? -
Populate db.sqlite in Django: localhost AND production
A newbie-type of question. I have a new website with a database that holds some objects (let's say cars) plus user session data (device, username). When I was developing it, whenever I needed to add more cars, I would simply add them either with a local script or in localhost/admin. Then I would just copy db.sqlite file to production that was in test phase yet. Now that I will have some users this action would delete their data obviously. And it feels a bad practice anyway. So what is the simplest way to add a number of records programmatically to production? I could run my script directly on the server and add data this way - straight into production. Or could add one by one via www.website.com/admin . But in this case, I will not have those entries in my development environment (I'd like to keep data mirrored so that it is easier and quicker to debug things). I could probably copy db.sqlite file from production back to development, but I guess it is also a wrong way. Any advice or links are highly appreciated. -
When new row inserted to database table, django can detect it
I am working on Django web application project. I am interested, if there is any tool or technique that When new row inserted to database table, django can detect it Use case is: User A inserts some data in Shop Stock table, and all other users knows there is a change in stock. -
Troubleshooting mysql database connections in django python when using multiprocessing
OS: CentOS 8 4.18.0-240.15.1.el8_3.x86_64 Python: 3.8 Django: 3.1.7 Apache: 2.4.37-30 Mariadb: 3:10.3.27-3 I have a website built in django and served via Apache via wsgi. The application makes use of multiprocessing. I wrote a decorator with which I decorate all of my views. Decorator: def counterDecorator(view_func, **kwargs): def wrapper(request, **kwargs): if not request.session.session_key: request.session.save() device_type = 'Unknown' if request.user_agent.is_mobile: device_type = 'Mobile' elif request.user_agent.is_tablet: device_type = 'Tablet' elif request.user_agent.is_pc: device_type = 'Desktop' elif request.user_agent.is_bot: device_type = 'Bot' keywords = {'s_key': request.session.session_key, 'ip_addr': request.META['REMOTE_ADDR'], 'browser': request.user_agent.browser.family, 'browser_version': request.user_agent.browser.version_string, 'operating_system': request.user_agent.os.family, 'operating_system_version': request.user_agent.os.version_string, 'device': request.user_agent.device.family, 'device_type': device_type, 'view_uri': request.path } p = Process(target=count, kwargs=keywords) p.start() return view_func(request, **kwargs) return wrapper Now as you can see this decorator prepares the data and then starts a new process, where a count function is called def count(s_key, ip_addr, browser, browser_version, operating_system, operating_system_version, device, device_type, view_uri): try: conn = create_connection() print(conn) except Exception as e: f = open(BASE_DIR + "/LOG.txt", "a") f.write(e) f.close() if UniqueUserModel.objects.filter(session_key=s_key).exists(): UUM = UniqueUserModel.objects.filter(session_key=s_key).get() UUM.viewsmodel_set.create(user_model=UUM, view=view_uri, view_time_stamp=datetime.datetime.now()) else: UUM = UniqueUserModel() UUM.session_key = s_key UUM.ip_addr = ip_addr if ip_addr != '127.0.0.1': UUM.country = GeoIP2().country(ip_addr).get('country_name') else: UUM.country = 'localhost' UUM.time_stamp = datetime.datetime.now() UUM.browser = browser UUM.browser_version = browser_version UUM.operating_system = operating_system UUM.operating_system_version = … -
How to save Parent django model in related model save
Have two models - Program and Segments. I need to calculate the total times in the program entry from the fields within the associated Segments. I attempted to do that by overriding the save methods, but when entering a new segment it won't update the program model entries unless I go directly into the program form and save/update it. I am missing how to get the segment Update to cause the Program Save/Update to happen. How do I give it the context to call the program save method within the Segment update (After the segment has been saved). Code of the models is: from django.db import models from django.urls import reverse from datetime import datetime, timedelta class Program(models.Model): air_date = models.DateField(default="0000-00-00") air_time = models.TimeField(default="00:00:00") service = models.CharField(max_length=10) block_time = models.TimeField(default="00:00:00") block_time_delta = models.DurationField(default=timedelta) running_time = models.TimeField(default="00:00:00") running_time_delta = models.DurationField(default=timedelta) remaining_time = models.TimeField(default="00:00:00") remaining_time_delta = models.DurationField(default=timedelta) title = models.CharField(max_length=190) locked_flag = models.BooleanField(default=False) deleted_flag = models.BooleanField(default=False) library = models.CharField(null=True,max_length=190,blank=True) mc = models.CharField(null=True,max_length=64) producer = models.CharField(null=True,max_length=64) editor = models.CharField(null=True,max_length=64) remarks = models.TextField(null=True,blank=True) audit_time = models.DateTimeField(null=True) audit_user = models.CharField(null=True,max_length=32) def calculate_time(self): total_run_time_delta = timedelta(minutes=0) for segs in self.segments.all(): total_run_time_delta += segs.length_time_delta self.running_time_delta = total_run_time_delta self.running_time = f"{self.running_time_delta}" hold_time = self.block_time.strftime("%H:%M:%S") t = datetime.strptime(hold_time,"%H:%M:%S") self.block_time_delta … -
multiple independent websockets connections
I have been playing around with django channels + angular. I have created an app that simply sends notifications to front end with a counter 1,2,3,4. It works fine, except if I open the page in multiple tabs. I am also not able to disconnect from the websocket, I can use unsubscribe but it does not really close the connection but that's more kind of a angular question. Anyways how can I make my socket multithread, So if I make multiple requests from the same computer but from different tabs it will work and 2 different instances of the consumer will be created therefore, If I load 2 pages in the same computer the counter should be different independently increasing counter. Do I need redis for that ? -
django using an Integerfield for sorting
I have a model which has an IntegerField. this field may change after creation of object. I wanna use it for the "trend" part in my project, like those objects with the larger number must shown at top. so what is the best way (efficient) to do this. my current idea is: class Map(models.Model): rank = models.IntegerField() and later use it like this: sorted_list = Map.objects.order_by("-rank")[:50] is this a good idea even if there are many requests for the trend page? -
Users gets an Qr code with link to django webpage with login required
My problem: A user gets an email with qrcode, the qrcode links to a website. But when the user is not logged in he cant reach the linked site (because of the login requirement). When the the user is logged in there is no problem, after scanning the qr he gets to the site. How can i make it user friendly when the user is NOT logged in. User gets qrcode, scans it and gets the login page of django. After logging in i want him to direct to the qr link directly. Is that possible ? Normally i post code, hower in this case i dont have any because the login proces is the standard one of django, and the qr link is just a decoded http link. -
I have difficulties saving the form data after form submission django
I have a form where user can create a team. But, somehow the form data never saved on the db after submission. The form page just refresh and return the form with the filled data. This happen to any form that I created for the project. I feel too confused as I tried every possible way I can think of, but to no avail. Any help could be appreciated. The model #model class Team(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True, blank=True) logo = models.ImageField(default='team.png', upload_to='teams_pic/') bg_img = models.ImageField(default='team_bg.png', upload_to='teams_pic/') cups = models.IntegerField(default=0) coach = models.ForeignKey(Profile, related_name="coach", on_delete=models.CASCADE) birth = models.IntegerField(blank=True) country = CountryField() state = models.CharField(max_length=100, choices=STATE_CHOICES) lga = models.CharField(max_length=100, choices=LGA_CHOICES) town = models.CharField(max_length=200, blank=True) creator = models.ForeignKey(Profile, related_name="creator", on_delete=models.CASCADE) fb = models.URLField(max_length=500, blank=True) tweet = models.URLField(max_length=500, blank=True) insta = models.URLField(max_length=500, blank=True) players = models.ManyToManyField(Profile, related_name='players', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) objects = TeamManager() def __str__(self): return str(self.name) class Meta: ordering = ('-created',) def get_absolute_url(self): return reverse('sport:team-detail-view', kwargs={'slug': self.slug}) __initial_name = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__initial_name = self.name def save(self, *args, **kwargs): ex = False to_slug = self.slug if self.name != self.__initial_name or self.slug == "": if self.name: to_slug = slugify(str(self.name)) ex = Team.objects.filter(slug=to_slug).exists() while … -
Why is Django not finding static files on S3?
I followed this tutorial in order to make Django use S3 when loading static files https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ When I try to upload new media files through my webapp they get uploaded directly on S3. However, when I try to load static files in my html templates and I inspect the links, those are still linked to my local drive. Why is Django not looking at S3 for static files in my case? settings.py: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME= "eu-central-1" AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3-website.{AWS_S3_REGION_NAME}.amazonaws.com' STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # STATICFILES_STORAGE = 'custom_storages.StaticStorage' MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' AWS_LOCATION = 'static' AWS_S3_FILE_OVERWRITE = False AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_DEFAULT_ACL = 'public-read' navbar.html: {% load static %} ... <img src="{% static '/images/logo1.png' %}" > When I reload and inspect my webpage I still see <img src="/static/images/logo1.png"> instead of a link to AWS. -
Django nested serialization is not serializing on read
I know this issue is pretty popular but can't figure this out. class SpaceTypeSerializer(serializers.ModelSerializer): class Meta: model = SpaceType fields = ['id', 'company_id', 'label', 'value', 'active'] class SpaceSerializer(serializers.ModelSerializer): class Meta: model = Space # space_type = serializers.PrimaryKeyRelatedField( # queryset=SpaceType.objects.all()) space_type = SpaceTypeSerializer(read_only=True) fields = ['id', 'location_id', 'name', 'description', 'active', 'space_type', 'group_reservations_active', 'seats'] I'm getting just the id for the space_type field. I tried the commented out part and get the exact same result. class Space(Model): location = ForeignKey( Location, on_delete=DO_NOTHING, blank=False, null=False, related_name='spaces' ) name = CharField(max_length=255) description = TextField(null=True) active = BooleanField(default=True) space_type = ForeignKey( SpaceType, on_delete=DO_NOTHING, blank=True, null=True, related_name='spaces' ) Here's my model. Not sure what else to try but I want my space_type to have the entire space type object serialized. Here's my query: def get(self, request, pk, format=None): space = Space.objects.select_related('space_type').get(pk=pk) serializer = SpaceSerializer(space) return Response(serializer.data) Not sure if i need the select_related in there but putting it in for verification purposes. -
IntegrityError at /profile NOT NULL constraint failed: tutorapp_profile.user_id
I am making a app for finding tutors where tutors need to log in and post their jobs in the web application. While developing the profile section for tutors, i am unable to add a feature of updating or uploading a new profile bio and profile picture. I'm new to django Here is my model of Profile in models.py class Profile(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE) image= models.ImageField(default = 'default.jpg',upload_to='profile_pics') bio=models.CharField(default = 'no bio',max_length=350) def __str__ (self): return f'{self.user.username} Profile' and its model form class UpdateProfile(forms.ModelForm): class Meta: model = Profile fields =['image','bio',] def clean(self): super(UpdateProfile, self).clean() return self.cleaned_data view of profile views.py def profile(request): if request.method == 'POST': p_form = UpdateProfile(request.POST, request.FILES) if p_form.is_valid(): p_form.save() return redirect('profile') else: p_form = UpdateProfile() context = { 'p_form': p_form } return render(request,'profile.html',context) urls.py urlpatterns = [ path('', views.index, name='index'), path('home', views.index, name='home'), path('signup', views.signup, name='signup'), path('postskill', views.postskill, name='postskill'), path('profile', views.profile, name='profile'), ] template of profile.html <img class="rounded-circle account-img" src="{{user.profile.image.url}}" height="100" width="100"> <h5> First Name: {{user.first_name}} </h5> <h5> Last Name: {{user.last_name}} </h5> <h5> Username: {{user.username}} </h5> <h5> Email: {{user.email}} </h5> <p> Bio: {{user.profile.bio}} </p> <button class="btn btn-primary" onClick="myFunction()"> UpdateProfile</button> <div id ="hide"> {% csrf_token %} <form method = "POST" enctype="multipart/form-data"> {% csrf_token %} {{ p_form|crispy … -
Django Multiple File Upload in UpdateView - not getting file information using request.FILES.getlist
I'm trying to get multiple file uploads working in my Django app. forms.py: from django.forms import ClearableFileInput class CountForm(forms.ModelForm): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) class Meta(): model = Count ... views.py: class count_modal(UpdateView): model = Count form_class = CountForm template_name = 'count_modal.html' pk_url_kwarg = 'count_id' def get_form_kwargs(self): kwargs = super(count_modal, self).get_form_kwargs() return kwargs def form_valid(self, form): obj = form.save() print(self.request.FILES.getlist('file_field')) ... My template is a generic form using enctype='multipart/form-data'. When I try to print out the file upload, it always comes up with an empty list. I'm planning to upload this to a different model, but for now I'm just trying to get the files in my view. -
Unable to resolve ModuleNotFoundError when deploying a Django App on Heroku
I keep getting the following error in my logs when I try to deploy my app on Heroku: 2021-03-16T19:03:43.053580+00:00 heroku[web.1]: Starting process with command `gunicorn todo.wsgi:application` 2021-03-16T19:03:46.709810+00:00 app[web.1]: [2021-03-16 19:03:46 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-03-16T19:03:46.711200+00:00 app[web.1]: [2021-03-16 19:03:46 +0000] [4] [INFO] Listening at: http://0.0.0.0:14087 (4) 2021-03-16T19:03:46.714536+00:00 app[web.1]: [2021-03-16 19:03:46 +0000] [4] [INFO] Using worker: sync 2021-03-16T19:03:46.720381+00:00 app[web.1]: [2021-03-16 19:03:46 +0000] [9] [INFO] Booting worker with pid: 9 2021-03-16T19:03:46.726148+00:00 app[web.1]: [2021-03-16 19:03:46 +0000] [9] [ERROR] Exception in worker process 2021-03-16T19:03:46.726159+00:00 app[web.1]: Traceback (most recent call last): 2021-03-16T19:03:46.726161+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-03-16T19:03:46.726163+00:00 app[web.1]: worker.init_process() 2021-03-16T19:03:46.726164+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process 2021-03-16T19:03:46.726164+00:00 app[web.1]: self.load_wsgi() 2021-03-16T19:03:46.726164+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2021-03-16T19:03:46.726165+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-03-16T19:03:46.726166+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-03-16T19:03:46.726167+00:00 app[web.1]: self.callable = self.load() 2021-03-16T19:03:46.726167+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2021-03-16T19:03:46.726167+00:00 app[web.1]: return self.load_wsgiapp() 2021-03-16T19:03:46.726168+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2021-03-16T19:03:46.726168+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-03-16T19:03:46.726169+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app 2021-03-16T19:03:46.726169+00:00 app[web.1]: mod = importlib.import_module(module) 2021-03-16T19:03:46.726170+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2021-03-16T19:03:46.726170+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-03-16T19:03:46.726170+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2021-03-16T19:03:46.726171+00:00 app[web.1]: File "<frozen importlib._bootstrap>", … -
Django Project ||Create a Signup module. . The user will get registered once the admin will approve it
Create a Signup module. Users will be required to register themself in the application. The user will get registered once the admin will approve it. -
Django celery[redis] is not working ! plz help me :(
I use DRF because Build API Server, When Clients register my app, I send register email to client, My Settings Window 10 Django 3.1.7 Python 3.8.7 pip install celery[redis] Here is my Code Tree Photo here Here is My Code celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.prod') app = Celery('config') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') __init__.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) task.py from django.core.mail import EmailMessage from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode from django.utils.encoding import force_bytes from django.contrib.auth import get_user_model from celery import shared_task from .tokens import account_activation_token User = get_user_model() @shared_task def task_send_email(user_pk, validated_data): user = User.objects.get(pk=user_pk) message = render_to_string('accounts/account_activate_email.html', { 'user': user, 'domain' : 'localhost:8000', 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user) }) mail_subject = 'Hello' to_email = validated_data['email'] email = EmailMessage(mail_subject, message, to=[to_email]) email.send() serializers.py def create(self, validated_data): user = User.objects.create(**validated_data) user.set_password(validated_data['password']) user.save() # Celery - Send Eamil task_send_email.delay(user.pk, validated_data) # Here!! Not Working T_T EmailSendHistory.objects.create( email_address = user.email, ) return user I try to redis-server celery -A config worker -l info python manage.py runserver I'm looking forward to sending an e-mail when I sign up for membership. However, … -
Django relation "users_driverregistration" does not exist
I changed django models ande deployed new version to the server. In admin page I see an error relation "users_driverregistration" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "users_driverregistration" I tried to update database via python3 manage.py makemigrations python3 manage.py migrate But received error File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards field, File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 447, in add_field self.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 137, in execute cursor.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/usr/local/lib/python3.7/site-packages/sentry_sdk/integrations/django/__init__.py", line 467, in execute return real_execute(self, sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, … -
How does postgreSQL structure Django Array Fields in database
How does PostgreSQL structure an ArrayField like: class House(models.Model): people_ids = ArrayField(models.IntegerField(), default=list, blank=True) in database? Does it generate an auxiliary table with the numbers as Ids and then another table with the Id pairs? Like: House Id Name 1 MyHouse People Id 1 2 House_People House_Id Person_Id 1 1 1 2 So as to have, for example, people 1 and 2 in house "MyHouse"? -
django auto login after UserCreationForm
I'm using one function to sign up and sign in user. The sign-in is working smoothly, however, when the user is registered it doesn't automatically login into his dashboard. Any suggestions? Thank you. form: class SignUpForm(UserCreationForm): class Meta: model = User fields = ('email','username','password1','password2',) labels = { 'email' : 'Email address', } .view: def index(request): # SIGN UP form = SignUpForm() login_form = CustomAuthForm() if request.method == "POST": if request.POST.get('submit') == 'sign_up': form = SignUpForm(request.POST) if form.is_valid(): auth.login(request) form.save(); messages.success(request, "Successfully registered.") return redirect("dashboard") elif request.POST.get('submit') == 'sign_in': #Log in login_form = CustomAuthForm(data = request.POST) if login_form.is_valid(): username = login_form.cleaned_data.get('username') password = login_form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.success(request, "Successfully logged in.") return redirect('dashboard') else: messages.success(request, "Error credentials.") else: messages.success(request, "Error.") return render(request, 'index.html', context={'form':form,'login_form':login_form}) -
Django Image is not added to media folder
So the thing is that in production code with media files is not working (image of model is not added there). If you need some details please write! Thank you for your help ) project configuration <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For … -
What are the methods for working with a self-referential model in a Django view?
I'm creating a virtual library in Django 3.1.5 and would like to show users books based on subjects that the books and users have in common. To make this a bit more powerful I plan on using a self-referential subject model. This will allow me to do a lot of things like suggest or show related books to users (e.g. I can show a user who's related to the subject Programming books that are relevant to Python, Django and Flask even though the user isn't related to those subjects directly), or create a dynamic library filter. Here are the subject fields that I have in my model: class SubjectType(models.Model): name = models.CharField(max_length=35) def __str__(self): return self.name class Subject(models.Model): name = models.CharField(max_length=255) subject_type = models.ForeignKey(SubjectType, on_delete=models.PROTECT) children = models.ManyToManyField("self", blank=True, related_name="parents", symmetrical=False) def __str__(self): return self.name My problem is that I'm fairly new to all of this, and while I've come across quite a bit of information regarding setting up self-referential models, I'm having a bit of trouble finding the right combination of QuerySet and view methods for efficiently querying such a model. And I would appreciate it if anyone could point me in the right direction. E.g.: How might I … -
When a registered user tries to add a product in cart it says Internal Server Error: /update_item/
When a guest user adds a products it works fine but when a registered user tries to add product in the cart it gives a error. Internal Server Error: /update_item/ Traceback (most recent call last): File "C:\Users\varuni\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\varuni\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\varuni\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: updateItem() missing 1 required positional argument: 'customer' Here is my updateItem in views.py: def updateItem(request, customer): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action: ',action) print('productId: ',productId) product = Product.objects.get(id = productId) order, created = Order.objects.get_or_create(customer = request.user.customer, complete= False) orderItem, created = OrderItem.objects.get_or_create(order= order, product= product) if action=='add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove' : orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('item added', safe=False) this is my store.html where the action of add to cart button is defined: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> {% for prod in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{prod.imageURL}}"> <div class="box-element product"> <h6><strong>{{prod.name}}</strong></h6> <hr> <button data-product={{prod.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <a class="btn btn-outline-success" href="#">View</a> <h4 …