Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Field 'person_id' expected a number but got ''
i want to ask about my error , exactly the problem is that i pass a parameter myid to my method newpost , it is working good and i can print it before if request.POST.get('postsubmit') but after this if, when i print it or try to use it, it appears as blank '' i really did not understand the problem please help def newpost (request , myid ): print(myid) assert isinstance(request, HttpRequest) if request.method == 'POST' & request.POST.get('postsubmit') : print(myid) if request.POST.get('postsubmit'): print( myid) if myid not in blockedperson : print ("not blocked") savepost=post() savepost.person_id= myid savepost.content=request.POST.get('postcontent') savepost.p_date=dt.datetime.now() savepost.save() else : blocked="sorry you are blocked , you can not share posts, contact with IT to more information at 437819147@kku.edu.sa" return render (request,'home.html',{'block':blocked}) allpost=post.objects.all() allperson=person.objects.all() allstudent=student.objects.all() allteacher=teacher.objects.all() allcomp=company_rep.objects.all() return render (request,'home.html',{'posts':allpost , 'person':allperson,'student':allstudent,'teacher':allteacher,'comp':allcomp}) error is here (my id is 437819147) to be clear Performing system checks... System check identified some issues: WARNINGS: app.company_rep.comp_id: (fields.W122) 'max_length' is ignored when used with IntegerField. HINT: Remove 'max_length' from field app.person.person_id: (fields.W122) 'max_length' is ignored when used with IntegerField. HINT: Remove 'max_length' from field app.post.person_id: (fields.W122) 'max_length' is ignored when used with IntegerField. HINT: Remove 'max_length' from field app.post.post_code: (fields.W122) 'max_length' is ignored when used … -
How to style Radio button in Django Forms
How can I modify these Radio Buttons? And also align them to horizontal and remove these bullet form buttons. forms.py class CustomerForm(ModelForm): gender = forms.ChoiceField(choices = Customer.GenderChoice, widget=forms.RadioSelect()) class Meta: model = Customer fields = ('first_name','last_name','address','phone','gender','email','password') widgets = { 'first_name': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'last_name': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'address': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'phone': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'email': forms.EmailInput(attrs={'class': 'form-control form-control-sm'}), 'password': forms.PasswordInput(attrs={'class': 'form-control form-control-sm'}) } -
IntegrityError 1048: "Column cannot be null"
In a project I have the apps users and comments, connected via ForeignKey. If I edit a user who doesn't have a comment, I can do that without without any problem. I can even add a comment. But when I try to save/patch any User data of a User that already has a comment, I get the IntegrityError. users\models.py: class User(AbstractBaseUser): created_at = models.DateTimeField(auto_now_add=True, editable=False)) .... #nothing special here comments\models.py: class Comments(models.Model): created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True, editable=False) modified_at = models.DateTimeField(auto_now=True, editable=False) created_by = models.ForeignKey(User, null=True, editable=False, related_name='%(class)s_created', on_delete=models.SET_NULL) modified_by = models.ForeignKey(User, null=True, editable=False, related_name='%(class)s_modified', on_delete=models.SET_NULL) type = models.CharField(max_length=50, blank=True, default='') content = models.CharField(max_length=100, blank=True, default='') owner = models.ForeignKey(User, null=True, blank=True, related_name='comments', on_delete=models.SET_NULL) The Trace in the Error Message points to the line cmnt.save() in the function update in the users\serializers.py, looking like this: def update(self, instance, validated_data): info = model_meta.get_field_info(instance) #extract nested user information to handle those separately ... ... comments_data = validated_data.pop('comments', None) ... ... # update user fields # Simply set each attribute on the instance, and then save it. # Note that unlike `.create()` we don't need to treat many-to-many # relationships as being a special case. During updates we already # have an instance pk … -
Renaming the field or using the right filter with django
I accidentaly named one of the fields "type" with django. Is there a way to rename it or can I still use the filter for that 'type' I understand that 'type' is a built-in function and it tries to use it and gives me errors. class Product(models.Model): name = models.CharField(max_length=60) type = models.ForeignKey(CarType, on_delete=models.DO_NOTHING, null=True, blank=True) year_released = models.PositiveIntegerField(default=0) description = models.TextField(null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) manufacturer = models.CharField(max_length=60,null=True, blank=True) def get_absolute_url(self): return reverse('product-detail', kwargs={"id": self.id}) class HydrogenView(ListView): model = Product queryset = Product.objects.filter(type='Hyrdogen') context_object_name = 'product' template_name = 'Hydrogen.html' -
Django admin lock time for wrong password
I want to set a security line in Django setting to lock the admin (superuser) if it has 3 times wrong password input. For example, for 3 hours. -
When a new model object is create, populate one of the values
I have tried this a few ways but am stuck and unsure where to go. My model (ExampleModStack) has a toadd_fk which is a foreign key obtained from a API. I want to use this to create a forign key refernce to the Toadd model when the ExampleModStack is created. I create ExampleModStack model by reading the API values so I need a funciton to do this for me. I was thinking of using signals pre_save function so that I can set the toadd relationship there. Here is my code: class ExampleModStack(models.Model): toadd_fk = models.IntegerField() toadd = models.ForeignKey( Toadd, null=True, on_delete=models.CASCADE, related_name='%(class)s_toadd' ) class Meta: verbose_name = 'example_mod_stack' verbose_name_plural = 'example_mods_stack' def __str__(self): return str(self.id) @receiver(pre_save) def referenc_product(cls, instance, **kwargs): cls.toadd = Product.objects.get(id=cls.toadd_fk) I can not get this to work though. Does anyone know a way to make this functional?