Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker & Django: Django is looking for a DB table before running migrations
When I run docker-compose, all containers start without errors except "catering-django-1". As I understand it, django looks for the "myapp_menu" table in the DB before running the migrations. However, everything works for me locally. That is, when I write "python3 manage.py migrate" in the console - everything works flawlessly. I can't figure out what the problem is for a long time and I hope for your help. Thank you! Docker-compose logs: Attaching to catering-django-1, catering-nginx-1, catering-postgres-1, catering-redis-1, catering-redis-commander-1, catering-worker-1 catering-redis-1 | 1:C 26 Aug 2023 17:55:06.942 # WARNING Memory overcommit must be enabled! Without it, a background save or replication may fail under low memory condition. Being disabled, it can also cause failures without low memory condition, see https://github.com/jemalloc/jemalloc/issues/1328. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect. catering-redis-1 | 1:C 26 Aug 2023 17:55:06.942 * oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo catering-redis-1 | 1:C 26 Aug 2023 17:55:06.942 * Redis version=7.2.0, bits=64, commit=00000000, modified=0, pid=1, just started catering-redis-1 | 1:C 26 Aug 2023 17:55:06.942 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf catering-redis-1 … -
Django celery is not processing the task
I am trying to tigger a process that runs in the background. I am calling this process using ajax call. I have setup celery/rabbitmq/flower to achieve this. In my app ->views.py def sync_now(request,sync_id): sync_obj=Sync.objects.get(id=sync_id) synchronize_data.apply_async(args=[sync_id]) result = synchronize_data.apply_async(args=[sync_id]) # Get the task ID task_id = result.id print("task id") return render something Tasks.py app = Celery('sync', broker='pyamqp://xxx:xxxx@localhost:5672/myvhost') @shared_task def synchronize_data(sync_id): try: sync_obj = Sync.objects.get(id=sync_id) # Your synchronization logic goes here sync_data(sync_id, sync_obj) return 'Success' # Return a result to indicate success except Exception as e: return str(e) # Return an error message in case of failure When I run this command - celery -A ipass worker -l info --pool=solo -- it appears like all the queued process gets triggered and sync_data is called multiple times. I had to manually kill the cmd But when I trigger this from the template I get only [2023-08-26 23:08:26,320: INFO/MainProcess] Task sync.tasks.synchronize_data[0c72b00b-acf1-48d2-ab44-6ddb678d62e8] received [2023-08-26 23:08:26,320: INFO/MainProcess] Task sync.tasks.synchronize_data[7c2c018f-cd6b-4dae-8cab-b18a572a5c92] received [2023-08-26 23:08:26,887: INFO/SpawnPoolWorker-32] child process 10588 calling self.run() [2023-08-26 23:08:26,888: INFO/SpawnPoolWorker-33] child process 11024 calling self.run() I am unable to debug, what is missing here ? Please let me know if you need more information. -
How to implement a time slot system in django?
# we need tuple for integer choices in django timeslot_weekday = ( (0, '9:00 - 10:00'), (1, '10:00 - 11:00') ) timeslot_weekend = ( (0, '10:00 - 11:00'), (1, '11:00 - 12:00') ) user_date = date(2023,1,15) if user_date.weekday() == 5 or user_date.weekday == 6: print(timeslot_weekend) else: print(timeslot_weekday) This code works as I am trying to understand how to implement an integer choice using a tuple that has the corresponding time slots. How do I go about this in the Django project? The one thing is I would need the user to select the date first in order to adjust the time slots of that particular time of the week. I hope this makes sense. -
NGINX redirect https://www.example.com to https://example.com
I want to redirect my https://www.example.com to my https://example.com domain. I managed it to make a redirect without the SSL https:// but when I add it to my domain an 400 error gets thrown. This is my sites-available: server { error_log /var/log/nginx/error.log debug; root /var/www/project; index index.html; server_name example.ch; location / { try_files $uri $uri/ =404;} listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.ch/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.ch/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.ch) { return 301 https://$host$request_uri; } # managed by Certbot server_name example.ch; listen 80; return 404; # managed by Certbot } server { server_name www.example.ch; return 301 $scheme://example.ch$request_uri; } -
django form validation using "raise forms.ValidationError()"
I'm using a CustomLoginForm for login. In that form, I have created function level validation in forms.py file using forms.ValidationError(). But forms.ValidationError() not even works. I don't know what is the reason. But i'm using django messages, it pop up the messages. please help me why the form validation function not works forms.py class CustomLoginForm(forms.Form): email = forms.EmailField( label='Email', max_length=254, widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Enter your email'}), ) password = forms.CharField( label='Password', widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Enter your password'}), ) def clean(self): cleaned_data = super().clean() email = cleaned_data.get('email') password = cleaned_data.get('password') if email and password: user = authenticate(email=email, password=password) if user is None: raise forms.ValidationError("Invalid email or password. Please try again.") return cleaned_data views.py def login(request): if request.method == "POST": form = CustomLoginForm(request.POST) if form.is_valid(): user_email = request.POST.get("email") user_password = request.POST.get("password") user = authenticate(request, email = user_email, password=user_password) if user is not None: auth_login(request, user) messages.info(request, f"you are now logged in {user_email}") return redirect("home") else: messages.error(request, "invalid email or password or user not exist") else: messages.error(request, "invalid email or password or user not exist") form = CustomLoginForm() context = { "login_form" : form } return render(request=request, template_name="account/login.html", context=context) login.html {% load static %} {% load crispy_forms_tags %} {% block content %} <!--Login--> … -
ValueError at /register/ The view authenticate.views.register_user didn't return an HttpResponse object. It returned None instead
I not able to fix this problem this problem everytime showing views.register_user didn't return an httpresponse. Also registering of user not happening properly, everytime showing this. Yesterday it was showing fine but today showing error. So, fix this error and how solve this problem. I have posted my detail code, please look up. Also I have applied in stackoverflow answers but nothing happening. Below my code: views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate,login,logout from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from .forms import SignUpForm def register_user(request): if request.method == 'POST': form=SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(request, username=username, password = password) login(request,user) messages.success(request,('You Have Been Registered!')) return redirect('home') else: form = SignUpForm() context = {'form': form} return render(request,'authenticate/register.html',context) register.html {% extends 'authenticate/base.html' %} {% block content %} <h2 class="text-center">Register</h2> <div class="col-md-6 offset-md-3"> <form method="POST" action ="{% url 'register' %}"> {% csrf_token %} {% if form.errors %} <p>Your Form Has Errors.....</p> {% endif %} {{ form.as_p }} <input type="submit" value="Register" class="btn btn-secondary"> </form> </div> <br/><br/> {% endblock %} forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class SignUpForm(UserCreationForm): email = forms.EmailField(label="",widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Email Address'})) first_name = forms.CharField(label="",max_length=100, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'First … -
Django Membership model registration
i have some issues with the following code. I have an authentication system that works fine. After user registers the account, django send a email with token for account confirmation. it works fine. now i want to add some code to save automatically free membership parameter when user click on activation link. there is something of wrong in my code: MEMBERSHIP_CHOICES = (('Premium', 'PREMIUM'), ('Free', 'FREE') ) class Membership(models.Model): slug = models.SlugField(null=True, blank=True) # name = models.CharField(max_length=100) description = models.TextField() membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free',max_length=30) price = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) def __str__(self): return self.membership_type def account_activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = Customer.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() # Create a free membership free_membership = Membership.objects.get(membership_type='Free') # Convert the Membership object to string # free_membership_str = str(free_membership) print(free_membership) # Create a new UserMembership # user_membership = UserMembership.objects.create(user=user, membership=free_membership.membership_type) user_membership = UserMembership.objects.create(user=user, membership=free_membership) # user_membership = UserMembership.objects.create(user=user, membership=self.free_membership) user_membership.save() # # Creating a new UserSubscription # user_subscription = Subscription.objects.create(user_membership=user_membership) # # user_subscription = Subscription() # # user_subscription.user_membership = user_membership # user_subscription.save() # # return user login(request, user) return redirect("homepage:homepage") else: return render(request, "account/registration/activation_invalid.html") if i … -
How can i get filter value to the particular view?
I want to get the filter value and pass it to the view to display it on another template, enter image description here this is the view I want the filter value in, is there a way I can get the filter value or get the filtered data whenever the filter is applied in the admin panel I want the filtered data or the filter name which I would apply to filter the model -
How can I make a user registration form using a model which extends a base user model?
I'm familiar with Python, but not much with Django. My first instinct was to use the __init__() and super() methods to allow a form class to inherit another, but then I came to the thought that maybe this isn't possible, as I haven't seen anything of the sort in Django's documentation. My models are as follows: models.py class UserAccountManager(BaseUserManager): def create_user(self, email, username, full_name, password=None): user = self.model( email = self.normalize_email(email), username = username, full_name = full_name, ) # the superuser method is also present, it has the same fields, but is cut for readability return user class UserAccount(AbstractBaseUser): # basic information fields such as username, email, etc. # also is the model which has the permissions, USERNAME_FIELD, and REQUIRED_FIELDS class BuyerAccount(models.Model): # extension of the base user, which will have additional information if needed user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) shipping_address = models.CharField(max_length=250) billing_address = models.CharField(max_length=250) def __str__(self): return self.user.username # the admin panel will return an error if I leave it at self.user The models work as expected and there is no issue with them. I can view, add, and edit them as necessary. However, when I went to give them custom views, I ran into some issues. admin.py class … -
Django model class method using wrong `self`
When I navigate to the admin page or my generic view for this model Loan I get the following error: File "library_app/catalog/models.py", line 118, in __str__ return f'{self.book.title} ({self.id})' AttributeError: 'NoneType' object has no attribute 'title' I've managed to track this down to the __str__ function of my BookInstance class. class Loan(models.Model): book_instance = models.OneToOneField(BookInstance, on_delete=models.RESTRICT) user = models.ForeignKey(User, on_delete=models.RESTRICT) date = models.DateField( default=django_timezone.now, help_text='Date borrowed' ) due_back = models.DateField( default= django_timezone.now() + datetime.timedelta(30), help_text='Date due to be returned' ) returned_date = models.DateField(null=True, blank=True, help_text='Date book was returned') class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) book = models.ForeignKey(Book, on_delete=models.RESTRICT, null=True) LOAN_STATUS = ( ('m', 'Maintence'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) status = models.CharField( max_length=1, choices=LOAN_STATUS, blank=True, default='m', help_text='Book Availability' ) def __str__(self): return f'{self.book.title} ({self.id})' I'm guessing that in these pages it when the __str__ method is called the wrong self variable is being used. I have no idea how to fix this so any tips would be appreciated. -
Atomic transaction in django
I have a view which updates object in database. Should I make this view atomic ( @transaction.atomic)? I want to eliminate data races (for example two requests update value at the same time) My code: @api_view(["POST"]) @transaction.atomic def employee_increase(request): logger.info(f"Increase sallary: {request.data}") serializer = IdSerializer(data=request.data) serializer.is_valid(raise_exception=True) employee = get_object_or_404(Employee, pk=request.data["id"]) old_sallary = employee.sallary employee.sallary = int(old_sallary * (1 + int(request.data["increase_percent"]) / 100)) employee.save() -
Django requirements file package is not installed in the selected environment
I want to create a live chat project with Django and Nextjs and I'm running into a problem. I'm not sure why after installing channels and channels-redis , when I try to import the package inside the files in not getting recognized ( import channels.db could not be resolved ), and in my requirements.txt file those 2 packages show as package is not installed in the selected environment . And I'm getting this error WebSocket connection to 'ws://127.0.0.1:8000/' failed: (I've tried with ws://localhost:8000/ too) when my frontend tries to access the backend. Please let me know what can I do to fix this. Thank you! I've tried to create this project with virtualenv and poetry, and I get the same problem with both. This is the code I have for the chat : settings.py file: WSGI_APPLICATION = 'backend.wsgi.application' ASGI_APPLICATION = "backend.asgi.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis", "6379")], }, } } asgi.py file import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from . import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') django_asgi_app = get_asgi_application() # application = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) routing.py file … -
How to make constraints at the model level so that two model fields cannot be equal to the same?
I need a check at the model or database level that user_1 is not equal to user_2 That it's not the same user It is important for me that it is impossible to create such a record in the database class SomeModel(Model): user_1 = Foreignkey(...) user_2 = Foreignkey(...) I tried to look for various validators, but at the model level, I can only fetch the data of a specific field. I need something similar to UniqueConstraint but without the ability to create at least 1 such record -
character encoding when translating Django and pushing to bitbucket
Using Linux Fedora, and PyCharm both English versions 1, I am in the process of translating the content using the i18n built-in Django. When I write python manage.py compilemessages I get: 'latin-1' codec can't encode character '\u201c' in position 5: ordinal not in range(256) This '\u20ic' refers to Double quotes. The file to translate has double quotes. When I push to bitbucket, even though it does push it, I get this message xkbcommon: ERROR: /usr/share/X11/locale/iso8859-1/Compose:49:29: string literal is not a valid UTF-8 string I went to check the file encodings in PyCharm and was disgusted to see that it was not UTF-8 but some ascii variant. I changed to UTF-8 but nothing happened, I can't compile the messages in the .po file This is a snippet of the Django file that because it has double quotes, it can't be compiled #: scaffoldapp/templates/index.html:279 msgid "Life is life." msgstr "la vida es la vida" #: templates/account/account_inactive.html:5 #: templates/account/account_inactive.html:8 msgid "Account Inactive" msgstr "" I already explained above what I had tried -
django admin login CSRF verification failed. Request aborted
I am building an django application. Everything is working locally. But after uploading it to the production server with DEBUG=True. I am getting csrf error when trying to login to the admin panel. My site is serving on https://api.example.com. My settings.py: ALLOWED_HOSTS = ["*"] CSRF_TRUSTED_ORIGINS = ["https://*.example.com"] CSRF_COOKIE_DOMAIN = '.example.com' CSRF_COOKIE_SECURE = True What is the problem here? -
How to update widget attribute based on user role in Django
I have this custom widget: class RelatedFieldWidgetCanAdd(widgets.Select): def __init__(self, related_model, related_url=None, can_add_related=True, *args, **kw): self.can_add_related = can_add_related super(RelatedFieldWidgetCanAdd, self).__init__(*args, **kw) if not related_url: rel_to = related_model info = (rel_to._meta.app_label, rel_to._meta.object_name.lower()) related_url = 'admin:%s_%s_add' % info # Be cautious, as "reverse" is not allowed here self.related_url = related_url def render(self, name, value, *args, **kwargs): self.related_url = reverse(self.related_url) output = [u'<div class="d-flex">'] output.append(super(RelatedFieldWidgetCanAdd, self).render(name, value, *args, **kwargs)) if self.can_add_related: output.append(u'<a href="%s?_to_field=id&_popup=1" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % (self.related_url, name)) output.append(u'<img src="%sadmin/img/icon-addlink.svg" width="20" height="50" class="pb-2 mx-2" alt="%s"/></a>' % (settings.STATIC_URL, _('Add Another'))) output.append(u'</div>') return mark_safe(u''.join(output)) And this is how I'm using it in form.py: class LeaveForm(forms.ModelForm): ... leave_type = forms.ModelChoiceField( queryset=LeaveType.objects.all().order_by('-pk'), empty_label='--------', widget=RelatedFieldWidgetCanAdd( LeaveType, related_url='leave_type_add' ) ) Now, if I'm logged in as a superuser in my dashboard, I can see the + button to create a related object. That's fine, but when I'm logged in as a normal user, it allows me to add related data. I know it's because I've set can_add_related to True by default. I want to update it while rendering it by checking the user's is_superuser or is_admin attribute. I tried to access the Request inside the widget, but I don't have access to the Request object. So, I … -
MultiValueDictKeyError at
list_entries() save_entries() get_entry() above functions are pre defined at util.py file. This is views.py code for saving a new page. Defining function for Creating new page. def createNewPage(request): if request.method == "GET": return render(request, "encyclopedia/createNewPage.html") else: title = request.POST['title'] content = request.POST['content'] titleExist = util.get_entry(title) if titleExist is not None: return render(request, "encyclopedia/error.html",{ "massage": "The page you would like to add is already exist." }) else: util.save_entry(title, content) html_content = convert_md_to_html(title) return render(request, "encyclopedia/entry.html",{ "title": title, "content": html_content }) This is showing in Django MultiValueDictKeyError at /createNewPage/ 'title' Request Method: POST Request URL: http://127.0.0.1:8000/createNewPage/ Django Version: 4.2.4 Exception Type: MultiValueDictKeyError Exception Value: 'title' Exception Location: C:\Users\fayek\Desktop\Django\venv\Lib\site-packages\django\utils\datastructures.py, line 86, in getitem Raised during: encyclopedia.views.createNewPage Python Executable: C:\Users\fayek\Desktop\Django\venv\Scripts\python.exe Python Version: 3.11.4 Python Path: ['C:\Users\fayek\Desktop\Django\wiki', 'C:\Program Files\Python311\python311.zip', 'C:\Program Files\Python311\DLLs', 'C:\Program Files\Python311\Lib', 'C:\Program Files\Python311', 'C:\Users\fayek\Desktop\Django\venv', 'C:\Users\fayek\Desktop\Django\venv\Lib\site-packages'] I'm working on a project of CS50-Web course(Projet-01[wiki]). when I'm trying to save a new page it's leading me to this error. I couldn't figure it out why this error occurring. -
Show models.DateField value in django template
I have to render the value of models.DateField() in the django template for a countdown functionality. For the DateField I will add the value in the django admin and I need that value in the Front-End. I tried to access the value by writing obj.field(DateField) but it doesn't render the value. Please have a look at the code below, you will understand easily. Any help would be greatly appreciated. I have a model like this: class FeaturedProduct(BaseModel): type = models.CharField(max_length=255, choices=ProductTypeChoices.choices) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='featured_products') daily_deal_countdown = models.DateField(blank=True, null=True) class Meta: unique_together = ('type', 'product') def __str__(self): return str(self.product) + '-' + str(self.type) In the views context I passing the daily_deals like this: context = {'products': products, 'featured': featured_products, 'bestseller': bestseller, 'new_arrival': new_arrival, 'daily_deal':daily_deal, 'cartItems': cartItems, 'cartTotal': cartTotal} In the template I am rendering like this: {% for product in daily_deal %} <div class="daily-deal-countdown" data-countdown-date="{{ product.daily_deal_countdown }}"></div> {% endfor %} In the above template the value for the field daily_deal_countdown shows nothing even though my Back-End has the value. Please help me get through. -
table dashboard_data has no column named end_year in Django
admin.py from .models import Data admin.site.register(Data) models.py class Data(models.Model): end_year = models.CharField(max_length=150, blank=True, null=True) intensity = models.IntegerField( blank=True, null=True) sector = models.CharField(max_length=150, blank=True, null=True) topic = models.CharField(max_length=150, blank=True, null=True) insight = models.CharField(max_length=150, blank=True, null=True) url = models.CharField(max_length=150, blank=True, null=True) region = models.CharField(max_length=150, blank=True, null=True) start_year = models.CharField(max_length=150, blank=True, null=True) impact = models.CharField(max_length=150, blank=True, null=True) added = models.CharField(max_length=150, blank=True, null=True) published = models.CharField(max_length=150, blank=True, null=True) country = models.CharField(max_length=150, blank=True, null=True) relevance = models.IntegerField( blank=True, null=True) pestle = models.CharField(max_length=150, blank=True, null=True) source = models.CharField(max_length=150, blank=True, null=True) title = models.CharField(max_length=150, blank=True, null=True) likelihood = models.IntegerField(blank=True, null=True) def __str__(self): return self.id views.py import json import os from django.shortcuts import render from django.templatetags.static import static from Blackcoffer.settings import BASE_DIR, STATIC_URL from .models import Data def dashboard(request): ROOT_FILE = os.path.join(BASE_DIR, STATIC_URL, 'jsondata.json') # json_data = open(ROOT_FILE) # json_load = json.load(json_data) with open(ROOT_FILE, 'r', encoding="utf-8") as data: parsed_json = json.load(data) for result in parsed_json: Data.objects.create( end_year = result['end_year'], intensity = result['intensity'], sector = result['sector'], topic = result['topic'], insight = result['insight'], url = result['url'], region = result['region'], start_year = result['start_year'], impact = result['impact'], added = result['added'], published = result['published'], country = result['country'], relevance = result['relevance'], pestle = result['pestle'], source = result['source'], title = result['title'], likelihood = result['likelihood'], ) … -
How to filter models by currently authenticated user using ModelViewSet in DRF
I'm working on Django project with Django Rest Framework. I have a model called Server and I want to filter the queryset by the currently authenticated user, but only if "by_user=true" is provided in query params. I'm using ModelViewSet to create the API endpoints. I have overrided the get_queryset and it works fine. But when I return is using super().list(request, *args, **kwargs) it returns the queryset without filtering. Only way I found to return the filtered queryset is by using Response(serializer.data). But I want to use the super().list() method. Any help would be appreciated. Thanks in advance. Here is Server Model: class Server(Model): name = CharField(max_length=100) owner = ForeignKey( settings.AUTH_USER_MODEL, on_delete=CASCADE, related_name="server_owner" ) category = ForeignKey(Category, on_delete=CASCADE, related_name="server_category") description = CharField(max_length=300, blank=True, null=True) members = ManyToManyField( settings.AUTH_USER_MODEL, related_name="server_members", blank=True ) def __str__(self): return self.name Here's Serializer: class ServerSerializer(ModelSerializer): class Meta: model = Server fields = "__all__" And Here's ViewSet: class ServerViewSet(ModelViewSet): queryset = Server.objects.all() serializer_class = ServerSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_class = ServerFilter def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) by_user = request.query_params.get("by_user", False) if by_user: queryset = queryset.filter(members=request.user) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) # return super().list(request, *args, **kwargs) -
Multiple ManyToManyFields with same through table
I have an Organization model and a custom link table model linking it to User like this: class Organization(models.Model): name = models.CharField(max_length=255) class OrganizationUser(models.Model): organization = models.ForeignKey( Organization, related_name="organization_users", on_delete=models.CASCADE ) user = models.ForeignKey( "users.User", related_name="organization_users", on_delete=models.CASCADE ) link_type = models.CharField( choices=LinkTypeChoices.choices, max_length=64, default=LinkTypeChoices.MEMBER ) To make it easier to query through to User from Organization, I want to set up a ManyToManyField with through="app_name.OrganizationUser". However, it would be nice to automatically filter this queryset based on the value of OrganizationUser.link_type. Is there any reason why I shouldn't or can't set up two ManyToManyFields on Organization pointing to User through OrganizationUser with different limit_choices_to values filtering for different values of OrganizationUser.link_type? For example, I would like to be able to write Organization.owners.all() and Organization.members.all(), running both through the same link table, and get different results. -
How to add current user as foreign key in Django serializer
I am writing a Serializer for my log model which contain User as a foreign key. How can I add the current user in log Serializer. Here is my log model: class Log(models.Model): id = models.AutoField(primary_key=True, null=False) title = models.TextField(null=False) user = models.ForeignKey(User, on_delete=models.CASCADE) impact = models.IntegerField() ease = models.IntegerField() confidence = models.IntegerField() def __str__(self): return f"{self.title},{self.pk}" Here is my log serializer: class LogSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(source='user.id' ,queryset=User.objects.all(), many=False) class Meta: model = Log fields = ['id','user','title','ease','impact','confidence'] but this is giving validation error. "user": [ "This field is required." ] Here is my views: class logsApiView(APIView): def post(self, request, id=None,format=None): data = request.data serializer = LogSerializer(data=data) serializer.is_valid(raise_exception=True) print('hey') serializer.save() response = Response() response.data = { 'message': 'Todo Created Successfully', 'data': serializer.data } return response -
RemoteDisconnected from celery task on docker when calling long running endpoints
I have a Django application running on docker-compose. In one of my background celery task, I am calling a Cloud Run endpoint. This endpoint takes a long time to complete: 60-80 seconds. celery task -- request -> Cloud Run ... process ... celery task <- response - Cloud Run I have confirmed on Cloud Run that the time out is set to 300 seconds, but I am seeing that the Celery task is raising ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')). Even when the Cloud Run itself is returning 200, my task is raising this error. Checking the logs on the celery side, I see that this error is raised when 61 seconds has passed from when the request was made. Is there a configuration on some layer that is terminating my request? I checked that the requests module itself does not a timeout unless specified, so I am suspecting something else. -
Django - How to use the results of a Django view query as an input to a different Django view query
I am new to coding / Django and apologize in advance if this question has been asked before. I have searched StackOverflow and haven't been able to find the answer I'm looking for. I am building a Django application that allows a user to search for a property record via a unique identifier (referred to as APN in my Django model). In addition, the application is designed to deliver consumer population data for the state in which a given property is located (e.g. California, Florida, etc.) When a user submits their APN search query, the application generates a page that displays the Address, City, and State. The state field is meant to be linked to a separate page that displays the state-level population data described above. For example, if the State for a given property is "Colorado", the user should be directed to a page that displays population data for Colorado (as opposed to a different state) when they click the link. Here are my models: class AnnualPopulation(models.Model): State = models.CharField(max_length=2, blank=True, null=True) Population_2022 = models.IntegerField(blank=True, null=True) Population_2023 = models.IntegerField(blank=True, null=True) class PropDots2(models.Model): APN = models.CharField(max_length=250, blank=True) Address = models.CharField(max_length=250, blank=True) City = models.CharField(max_length=250, blank=True) State = models.CharField(max_length=250, blank=True) Here … -
Django error on fly io app: django.db.utils.OperationalError: no such table: django_session
I have a Django application deployed on fly.io Sometimes when I do a database operation like login, signup, or a CRUD operation, it returns the error "django.db.utils.OperationalError: no such table: django_session". I think it's important to note I'm using sqlite3 I logged in to the fly ssh console and executed the commands: python manage.py makemigrations python manage.py migrate But the error is still showing almost every time I do a database operation from the UI of my app