Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python application doesnt work on GoDaddy Shared Hosting after SSL Certifcate change
I had my django application hosted on the GoDaddy shared hosting platform which i set up using the SetUp Python Application. It was all working fine but then the free CloudFare SSL certificate. Hence i had to rename the DNS servers and replace the old Cloudfare SSL certificate with a new GoDaddy SSL certificate. But since then the website has been showing Incomplete response received from application. I called goDaddy support but they asked me to check my code. I did and I find no issues in it. I am unable to find the reason behind this issue. When i checked the network tab, it is showing a 502 error. The link to my website is Mint Chalk Media Can anyone pls help me find a solution? -
Django best practice for varying querysets dependant on user permissions and database values
I am new to Django and just trying to work out the best way of implementing some business logic. I am representing access to AV devices in a building with multiple floors. Each floor is leased by a separate tenant. Each tenant has one or more users than can access one or more of the AV devices on the floor. There is a tenant admin responsible for defining the users and their devices per tenancy. I have three roles - superuser, tenant admin and tenant user. I have a set of tables in the DB that define the floors, AV objects on the floors and which tenants can access which objects. The admin of this in Django works fine. I now want to display this in a simple front end so that the following is possible: super user - sees each floor and then can see devices on a selected floor and operate them tenant admin - sees just their floors and can operate all devices on their floor(s) tenant user - sees just the floor and devices they have been allocated access to To my mind this can all be done in one one template with some view based … -
Django: annotate count of replies by user through relation of field
I am struggling with this queryset for days, here's the model with three classes, User, Category, Post: from django.db import models from django.db.models.deletion import CASCADE class User(models.Model): name = models.CharField() @property def most_reply_to(self): return self.post_setvalues('reply_to')\ .annotate(reply_to_count=Count('user'))\ .order_by('user') @property def most_replied_by(self): pass class Category(models.Model): name = models.CharField() class Post(models.Model): title = models.CharField() user = models.ForeignKey(on_delete=models.CASCADE) category = models.ForeignKey(on_delete=models.CASCADE) url = models.URLField() reply_to = models.URLField() The reply_to filed contains the information of user interactions, unfortunately it's not ForeignKey'ed to the Post model itself, but only to point to the url field of other post. What I'd like to achieve here, is to annotate each user with: the counts of replies received, grouped by (source) user; the counts of replies given to, grouped by (target) user; For the most_reply_to method, I have experimented as seen in my code, but the code only gave me count of replies to each individual post (from the user), not the total count of replies to each other users, I have lost in the aggregate/annotate logic here. For the most_replied_by method, I understand I need to start with the entire Post.objects.all() queryset, but I have no clue as how should I filter out those that are replies to … -
How to paginate a class-based list view with django-filters
Do you guys know how to paginate a generic class-based ListView that uses django-filters as a search bar? When I read some articles regarding this issue(which wasn't a lot for class-based views), it seems that django-filters and pagination don't work together very well. Here is my view: class StudentListView(OrganisorAndLoginRequiredMixin, generic.ListView): template_name = "leads/student_list.html" context_object_name = "leads" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = StudentFilter(self.request.GET, queryset=self.get_queryset()) return context def get_queryset(self): organisation = self.request.user.userprofile return Lead.objects.filter(organisation=organisation).order_by('first_name') I would really appreciate it if you guys could tell me what code I need to write for my view as well as what code I need to add into my template to make this work. I don't think the code for the actual filter and the template is necessary, but if you guys need it, I can add it to this question. Thanks. -
Why django gives TypeError mistake?
TypeError at/admin/ 'set' object is not reversible Only admin page gives error.Home page doesnt.How can i fix this?Help please. -
how to setup postgresql on Circle CI
I have the following build configuration that succeeded on Circle CI but i don't understand why postgresql result is actually grey. it look like its not working properly when i click on the database report: here is the report from the console: **************************************************** WARNING: No password has been set for the database. This will allow anyone with access to the Postgres port to access your database. In Docker's default configuration, this is effectively any other container on the same system. Use "-e POSTGRES_PASSWORD=password" to set it in "docker run". **************************************************** The files belonging to this database system will be owned by user "postgres". This user must also own the server process. The database cluster will be initialized with locale "en_US.utf8". The default database encoding has accordingly been set to "UTF8". The default text search configuration will be set to "english". Data page checksums are disabled. fixing permissions on existing directory /var/lib/postgresql/data ... ok creating subdirectories ... ok selecting default max_connections ... 100 selecting default shared_buffers ... 128MB selecting default timezone ... UTC selecting dynamic shared memory implementation ... posix creating configuration files ... ok running bootstrap script ... ok performing post-bootstrap initialization ... sh: locale: not found 2021-04-05 17:06:05.104 UTC … -
pythonanywhere django static files are not collected from application
The problem is that static files from Django app are not being collected in pythonanywhere. After the command python manage.py collectstatic In the directory /home/user/user.pythonanywhere.com/static Only the admin folder appears. settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' ] Css file location: +---myapp | +---static | | \---myapp | | \---css | | \---myapp.css When I run the command python manage.py collectstatic in my local command line, static files from the application are collected, the problem is in pythonanywhere. All actions are standard, I did everything strictly according to the guide, I cannot understand what's the matter. Thanks a lot I have read all the articles on this topic on pythonanywhere and everything I found on stackoverflow and in the documentation, but nothing helps to solve the problem. https://help.pythonanywhere.com/pages/DjangoStaticFiles https://help.pythonanywhere.com/pages/DebuggingStaticFiles/ https://help.pythonanywhere.com/pages/StaticFiles -
How to dynamically update a django form field queryset based on selection in previous field?
I currently have the following form and view: class CreatePreferenceForm(Form): object_1_type = ModelChoiceField(queryset=ContentType.objects.filter(model__in=['course', 'baseuser'])) object_1 = ModelChoiceField(queryset=Course.objects.all()) object_2_type = ModelChoiceField(queryset=ContentType.objects.filter(model__in=['course', 'timeblock'])) object_2 = ModelChoiceField(queryset=Course.objects.all()) class CreatePreferenceView(LoginRequiredMixin, FormView): template_name = 'crud/create_preference.html' form_class = CreatePreferenceForm success_url = '/crud/create-preference' What I want to achieve is: When the user selects the Course model in the object_1_type field, the object_1 queryset should be updated to be Course.objects.all(). Inversely, if they choose the BaseUser model, the queryset will be BaseUser.objects.all(). Equivalent logic will be applied to the second pair of fields, although with different models. I've researched this for some time and was able to find a few potential approaches, however, I am still struggling with implementing them. Advice or alternative approaches would be greatly appreciated. Potential Approaches: Use an Ajax call to update the frontend to filter out the portions of the queryset you do not want (so I'd start with having the queryset be both models and then remove all instances of the "wrong" model using Ajax). I haven't worked with Ajax before, so I'm unsure on how I would write this. Django form fields can be updated programmatically and it's theoretically possible to achieve what I'm looking for by updating the fields during … -
Django Docker How to only migrate in Container?
Question can be little unclear so let me explain. I have a Django Project and for this time I wanted to use Docker. So I dockerized my project from the tutorials on the internet. As Django users know, if you want to extend the user model you need to make migrations afterwards you edit the model So I was editing my custom user model and wanted to test a feature for my model. What I wanted to achieve was, test migrated version of my Django app on Docker container and if it fits my needs I would make the migration on local files. But after I ran the docker-compose exec web python manage.py make migrations users command my also local files changed. So my question is, if I want to test a feature on migrated version of my app can I test it on Docker container and then migrate on local machine? or did I not understand the logic of docker? docker-compose.yml version: '3.8' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/backend/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:13-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=admin - POSTGRES_DB=db - POSTGRES_PASSWORD=password volumes: postgres_data: -
Django Crispy forms Return missing labels in the browser
I am working with django forms recently and each time i add the |crispy tag as below on my forms, they come back missing labels in the browser. What could be the problem? Below is my form from the .html file. {% load crispy_forms_tags %} . . . <form method="post"> <fieldset class="form-group"> Enter details. </legend> {% csrf_token %} {{ form | crispy }} </fieldset> <button type="submit">Submit</button> </form> My form class from the forms.py file is below class MyPlanForm(forms.ModelForm): class Meta: model = MyPlan fields = [ 'title', 'intent', 'description' ] I have the latest version of django-crispy-forms which is a pip installation. I use chrome for development but the same issue happens in firefox. I really need help anyone. Thanks in advance! -
How I can compare content of fields?
I want to compare content of fields. It is work without errors, but fields arent comparing. Where if my misstake? views class check(DetailView): def get_object(self, **kwargs): print(kwargs) return test.objects.get(pk=self.kwargs['pk']) m = 5 if test.check1 == test.answer1: m=m-1 if test.check2 == test.answer2: m=m-1 if test.check3 == test.answer3: m=m-1 if test.check4 == test.answer4: m=m-1 if test.check5 == test.answer5: m=m-1 template_name = 'main/test_detail.html' html {% if m == 5 %} <a href={% url '' %}></a> {% elif m == 4 %} <a href={% url '' %}></a> {% elif m == 3 %} <a href={% url '' %}></a> {% elif m == 2 %} <a href={% url '' %}></a> {% elif m == 1 %} <a href={% url '' %}></a> {% elif m == 0 %} <a href={% url '' %}></a> {% endif %} Models class test(models.Model): answer1 = models.CharField() answer2 = models.CharField() answer3 = models.CharField() answer4 = models.CharField() answer5 = models.CharField() check1 = models.CharField(null=True, blank=True) check2 = models.CharField(null=True, blank=True) check3 = models.CharField(null=True, blank=True) check4 = models.CharField(null=True, blank=True) check5 = models.CharField(null=True, blank=True) -
Weird behavior in Django
we have interest and add_interest just like we did in the range app but with everything similar to range app and the correct url shown, the add_interest returns an interest page instead of the add_interest page and raise Interest matching query does not exist error. Where it should in the interest view, we just cannot figure out what is going on and continue please help us Traceback Switch to copy-and-paste view /opt/anaconda3/lib/python3.8/site-packages/django/core/handlers/exception.py in inner response = get_response(request) … ▶ Local vars /opt/anaconda3/lib/python3.8/site-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars /opt/anaconda3/lib/python3.8/site-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /Users/a123/Desktop/matemaker_project/matemaker/views.py in interest interest = interests.get(slug=interest_name) # search through genre interests for specified interest. … ▶ Local vars /opt/anaconda3/lib/python3.8/site-packages/django/db/models/query.py in get raise self.model.DoesNotExist( … ▶ Local vars view for individual interest pages def interest(request, genre_name, interest_name): context_dict = {} genre = Genre.objects.get(slug=genre_name) interests = Interest.objects.filter(genre=genre) # get interests related to genre interest = interests.get(slug=interest_name) # search through genre interests for specified interest. context_dict['genre'] = genre context_dict['interest'] = interest context_dict['genre_slug'] = genre.slug context_dict['interest_slug'] = interest.slug response = render(request, 'matemaker/intrest.html', context = context_dict) visitor_cookie_handler(request,response,Interest) return response @login_required def add_interest(request, genre_name): try: genre = Genre.objects.get(slug=genre_name) except Genre.DoesNotExist: genre = … -
I can't create another ForeignKey using Django
I'm working on a small Django Project, I would like to create a second ForeignKey in the same model, but it doesn't work after the migration I don't see the field in my table contact, this is my Models ( i have a Custom User Model and work fine ) from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) username = models.CharField(max_length=255, unique=False, blank=True, null=True) email = models.EmailField('email address', unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] This is my class Contact ( as you can see I try to add a foreign key called user ) from django.db import models from list.models import List from users.models import CustomUser class Contact(models.Model): list = models.ForeignKey(List, on_delete=models.DO_NOTHING, related_name="list") user = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING, related_name="user") greeting = models.CharField(null=True, blank=True, max_length=255) first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) title = models.CharField(null=True, blank=True, max_length=60) company = models.CharField(null=True, blank=True,max_length=60) phone = models.CharField(null=True, blank=True, max_length=60) def __str__(self): return self.first_name What i try to do : Each user can have Contacts Each Contact depend on a list -
Django iterate all values from zip
first I zip all my lists just like books= zip(ID, bookName, *detail) but as you see the detail has not only one element, I can not sure the number of list of detail. And the number is variable. Than loop over it in templates like: {% for ID, bookName, detail, in books %} <tr> <td>{{ ID}}</td> <td>{{ bookName }}</td> <td>{{ detail }} </td> </tr> {% endfor %} As I can not confirm the number of detail, I got the error message like "Need 3 values to unpack in for loop; got 5. " Is there any method to get the right loop times when the list is variable. -
URL Link Parameters
This is my templates, I'm attempting to make the genres and traits clickable links that render an existing that lists all other artists with the traits or within the genre. <h1>{{artist.stage_name}}</h1> <h6>{{artist.real_name}}</h6> <hr> Genre:<a href="">{{artist.artist_genre}}</a> <br> Tratis:{{artist.artist_trait.all|join:", "}} This is my current view. Do I have to query the genre's and traits separately? def ArtistProfileView(request, pk): artist = Artist.objects.get(id=pk) context = {'artist':artist, } return render(request, 'artist/artist_profile.html', context) These are my models class ArtistGenre(models.Model): genre_name = models.CharField('Genre', max_length=20) def __str__(self): return self.genre_name def get_absolute_url(self): return reverse('genre_detail', kwargs={'pk': self.pk}) class ArtistTrait(models.Model): trait_name = models.CharField('Trait', max_length=20) def __str__(self): return self.trait_name def get_absolute_url(self): return reverse('trait_detail', kwargs={'pk': self.pk}) class Artist(models.Model): stage_name = models.CharField('Stage Name', max_length=255) real_name = models.CharField('Birth Name', max_length=255, blank=True) artist_genre = models.ForeignKey(ArtistGenre, on_delete=models.CASCADE, related_name='artists') artist_trait = models.ManyToManyField(ArtistTrait, related_name='artists') date_added = models.DateField(auto_now_add=True, null=True) def __str__(self): return self.stage_name def get_absolute_url(self): return reverse('profile_artist', kwargs={'pk': self.pk}) These are my URLs urlpatterns = [ path('', views.ArtistIndex, name='index_artist'), path('artists/', views.ArtistListView.as_view(), name='artist_list'), path('profile/<int:pk>/', views.ArtistProfileView, name='profile_artist'), path('new/', views.ArtistCreateView.as_view(), name='new_artist'), path('edit/<int:pk>/', views.ArtistUpdateView.as_view(), name='edit_artist'), path('delete/<int:pk>/', views.ArtistDeleteView.as_view(), name='delete_artist'), path('genres/', views.GenreListView.as_view(), name='genre_list'), path('genre/<int:pk>/', views.GenreProfileView, name='genre_profile'), path('traits/', views.TraitListView.as_view(), name='trait_list'), path('trait/<int:pk>/', views.TraitProfileView, name='trait_profile') Thank You. -
Get Related model fields in django template
I am trying to fetch products and I want images of the same also with the product in the Django template. MODEL class Product(models.Model): title = models.CharField(blank=True,null=False,max_length=100) class ProductImage(models.Model): product = models.ForeignKey(to='products.Product', on_delete=models.CASCADE, default=None) image = models.ImageField(upload_to='images/product_inmages', null=False, blank=False) def __str__(self): return self.product.title -
How to revoke permission to edit Admin User in django admin
class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have an username") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField(verbose_name='email', max_length=80, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=100,null=True) last_name = models.CharField(max_length=100,null=True) phone_no = models.CharField(max_length=12, null=True) date_joined = models.DateField( verbose_name='date joined', auto_now_add=True) last_login = models.DateField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) address = models.CharField(max_length=500, null=True, blank=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] objects = MyAccountManager() def __str__(self): return self.email # def has_perm(self, perm, obj=None): # return self.is_admin def has_module_perms(self, app_label): return True I have a custom user model and I'm able to create groups without giving necessary permissions. I created a group by giving permission to view and change users. I added a staff user to that group without escalating them as an admin user or a superuser. But that user can edit admin user. How I can prevent users in that specific group … -
sentry not showing errors in issues
I have been using a Sentry for six months and it was works perfect But Sentry has not been showing errors in Dashboard>Issues since nine days ago errors saving in Transactions and showing in Dashboard>Performance but not showing in Dashboard>Issues i integrate sentry1.0.0 with django2.2.* how can fix this? how show errors in Dashboard>Issues with errors log? config in settings.py sentry_sdk.init( dsn="https://********************ac@o*****.ingest.sentry.io/******9", integrations=[DjangoIntegration()], traces_sample_rate=1.0, send_default_pii=True ) -
Django load wrong template
I am new to Django. I am trying to configure an app called 'faq', and an index page to display the different "apps", including the previous one. I was following the Learn Django site guide to decide what was best for the template structure. So, I configured myproject/settings.py to let load the template from templates folder: 'DIRS': ['templates'],. In the app folder myproject/apps/faq I have created a templates folder. In the app views myproject/apps/faq/views.py I defined the views to load the data from database and send it back to the template: from django.shortcuts import render from .models import * def faqs_view(request): faqs = FrequentAskedQuestion.objects.all() context = { 'faqs': faqs } return render(request, 'index.html', context) def faq_view(request, id): faq = FrequentAskedQuestion.objects.get(id=id) print(faq) context = { 'faq': faq } return render(request, 'detail.html', context) In the app folder I have created a URLconf configuration in myproject/apps/faq/urls.py: from django.urls import path from .views import faqs_view, faq_view urlpatterns = [ path('', faqs_view, name='faq-list'), path('<int:id>', faq_view, name='faq-detail'), ] A parenthesis here, since the first attempt I have tried to create a project templates folder and use the project views.py and urls.pyand it didn't work I decided to create another app called main. In the app folder … -
django How to optimize sql statement?
my code: i use django orm dynasty_li = ["USA", 'US', 'JPN'] data={} for dynasty in dynasty_li: data[dynasty]=People.objects.filter(dynasty=dynasty).order_by("-create_time")[:100] if use sql dynasty_li = ["USA", 'US', 'JPN'] data={} for dynasty in dynasty_li: sql="select * from people group by dynast='{dynast}' order by create_time DESC" data[dynasty]=query(sql) I think it should be group by, but it is impossible to extract the top N from the bottom based on each dynasty How to be more pythonic? -
How to filter a queryset with Foreign Key?
I've got three models like these: class Equipo (models.Model): alias=models.CharField(max_length=50, primary_key=True) lid1=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid1", on_delete=models.CASCADE) lid2=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid2", on_delete=models.CASCADE) lid3=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid3", on_delete=models.CASCADE) lid4=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid4", on_delete=models.CASCADE) gre1=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre1", on_delete=models.CASCADE) gre2=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre2", on_delete=models.CASCADE) gre3=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre3", on_delete=models.CASCADE) jlg1=models.ForeignKey(Corredor,limit_choices_to={'jor':True, 'giro':True, 'tipo': "Rider"}, related_name="jlg1", on_delete=models.CASCADE) jlg2=models.ForeignKey(Corredor,limit_choices_to={'jor':True, 'giro':True, 'tipo': "Rider"}, related_name="jlg2", on_delete=models.CASCADE) lid_sup=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid_sup", on_delete=models.CASCADE) gre_sup=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre_sup", on_delete=models.CASCADE) jlg_sup=models.ForeignKey(Corredor,limit_choices_to={'jor':True, 'giro':True, 'tipo': "Rider"}, related_name="jlg_sup", on_delete=models.CASCADE) ganador_e1=models.ForeignKey(Corredor,limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e1", on_delete=models.CASCADE) ganador_e2=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e2", on_delete=models.CASCADE) ganador_e3=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e3", on_delete=models.CASCADE) ganador_e4=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e4", on_delete=models.CASCADE) ganador_e5=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e5", on_delete=models.CASCADE) ganador_e6=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e6", on_delete=models.CASCADE) ganador_e7=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e7", on_delete=models.CASCADE) ganador_e8=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e8", on_delete=models.CASCADE) ganador_e9=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e9", on_delete=models.CASCADE) ganador_e10=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e10", on_delete=models.CASCADE) ganador_e11=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e11", on_delete=models.CASCADE) ganador_e12=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e12", on_delete=models.CASCADE) ganador_e13=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e13", on_delete=models.CASCADE) ganador_e14=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e14", on_delete=models.CASCADE) ganador_e15=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e15", on_delete=models.CASCADE) ganador_e16=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e16", on_delete=models.CASCADE) ganador_e17=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e17", on_delete=models.CASCADE) ganador_e18=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e18", on_delete=models.CASCADE) ganador_e19=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e19", on_delete=models.CASCADE) ganador_e20=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, … -
Django generate Secure Acccess Key Id and access Key Token
I am building a payment getway with different ideas. Currently i am using django-rest-auth and allauth to secure login the web application But i want to keep web login and payment api login separate. For example, you know aws give access key and access passwrd. and these are very different from origin email and password login. I want, when a user login to the application with their password and email, they able to generate an API Key, and they can use it in their own web application backend to authenticate with may web based payment getway to send request and get response. How can i do it? can anyone help me in this case? -
celery task scheduled differently?
I have a scheduled Celery task that fetches some data via an API, every 30 min. However, if it crashes or there's no new data, I want the task to retry 5 more times and then stop completely, i.e.(it shouldn't execute after every 30 min anymore). My code is as follows: @app.task(autoretry_for=(Exception,), retry_kwargs={'max_retries': 5}, retry_backoff=True) def my_func(): print('retrying') try: # do something print('i update') except Exception as exc: print("i don't update") celery conf: app.conf.beat_schedule = { 'my_func': { 'task': 'app.tasks.my_func', 'schedule': 1800.0 }, } I notice that the task does not stop execution after 30 min. Where am I going wrong? -
Manually set model fields in ModelForm
I have a model with a foreign key and a unique constraint as follows: class Menu(models.Model): tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) name = models.CharField(max_length=128) date_menu = models.DateField() class Meta: constraints = [ models.UniqueConstraint(fields=['tournament', 'name', 'date_menu'], name="unique_name_menu") ] I would like to create a form to add instance of Menu. However the value of tournament is set by the URL of the page. I do not want the user to be able to set it. For this I use a modelForm, excluding the tournament field : class MenuForm(forms.ModelForm): date_menu = forms.DateField(initial=datetime.datetime.now()) class Meta: model = Menu exclude = ['tournament'] Here is my view : def add_menu(request, tournament_slug): tournament = get_object_or_404(Tournament, slug=tournament_slug) form = MenuForm(request.POST or None) if form.is_valid() and formset.is_valid(): menu_id = form.save(commit=False) menu_id.tournament = Tournament.objects.get(pk=1) menu_id.save() # I get the integrity error only here return HttpResponseRedirect(reverse('admin')) return render(request, "view.html", {'form': form, 'formset': formset, "tournament": tournament}) My problem is that when I call the .is_valid() function on this form the uniqueness condition cannot be checked as the tournament field is not set. As a result I get an integrity error when calling the save function in the view. The question is : how can link the Menu instance created by the form … -
is there any possibility to translate variable text in django [closed]
using Django i18n module In a scenario where i have: _somevar = _(f'{settings.config.someparameter} overview') i need the parameter settings.config.someparameter to be translated as well for example when the parameter is "account" then _somevar would be equal to "profile overview" and the french translation "compte aperçu" i struggled to find a way to do this but find nothing even in Django documentation