Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
ImageField uploads with Django Admin but not with template
I have the following form hooked to my Django Admin: # forms.py class ProfileForm(ModelForm): class Meta: model = UserProfile fields = ('name', 'profile_pic') # admin.py class ProfileAdmin(ModelAdmin): form = ProfileForm admin.site.register(UserProfile, ProfileAdmin) # models.py class UserProfile(models.Model): user = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(upload_to='profile_image', null=True, blank=True) def __str__(self): return str(self.user) Now if I upload the profile_pic with Django Admin, everything works fine. However, if I submit the image through my template, it doesn't work. Here's my template: {% extends '_base.html' %} {% block content %} <form action="." enctype="multipart/form-data" id="userprofile_form" method="post" novalidate=""> <h1> Update your profile </h1> {% csrf_token %} <div> {{ form }} <button class="border-2">Update Profile</button> </form> {% endblock %} The corresponding view is this: @login_required def get_profile(request): profile = request.user.userprofile form = ProfileForm(instance=profile) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): form.save() return render(request, 'profile-edit.html', {'form':form}) In the view (inside if form.is_valid()), form.cleaned_data has value None for profile_pic. request.FILES is <MultiValueDict: {'profile_pic': [<InMemoryUploadedFile: dave_pic.png (image/png)>]}> What's wrong with my upload logic. As I said, the same works just fine with Django Admin. MEDIA_ROOT and MEDIA_URL are all set. -
How to install custom swagger in django rest framework. I want custom everything using json or yaml
I am new in Swagger Api Documentation and I searched lot of tutorial and i have read many blogs but i didn't find particular solution. I know how to implement using package drf swagger but i want to customise this for example: I want to do middle api url on top means ordering according to me and everything without change in my code. I saw swagger in node also in node one person is doing change everything means sorting, description, parameters, etc. Is it possible to do in django rest framework. -
How to access reverse relationship in django models?
I have two models one for User and another for storing CustomerInfo(user of type customer). class User(AbstractBaseUser): """ This is a class for user table which overrides functionalities of default django user model. Attributes: name (CharField): Name of a user. email (EmailField): Email address of a user. mobile (CharField): Phone number of a user. date_joined (CharField): When a user was added. last_login (CharField): Last login date time of a user. is_admin (CharField): If user is a admin or not. is_active (CharField): If user is active or not. is_staff (CharField): If user is staff or not. is_superuser (CharField): If user is a superuser or not. role (OneToOneField): One to one relationship with role table. """ name = models.CharField(max_length=80) email = models.EmailField(max_length=255, unique=True) mobile = models.CharField( validators=[ RegexValidator( regex=r"^\d{10,14}$", message="Phone number must be entered in format: '+999999999'. Up to 14 digits allowed.", ) ], max_length=15, unique=True, ) role = models.ForeignKey(Role, on_delete=models.SET_NULL, null=True) drivers = models.ManyToManyField( "self", through="DispatcherDriver", symmetrical=False ) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(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) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) USERNAME_FIELD = "mobile" REQUIRED_FIELDS = ["email", "name"] objects = UserManager() class Meta: db_table = "users" … -
why the Django admin login page throwing FieldError?
Something strange happened. I have created the custom user model. It was working properly until today. And I have no idea what has gone wrong. When I launch the admin page to login, I see below error after I click on 'login'. I use 'email' as an username FieldError at /admin/login/ Cannot resolve keyword 'username' into field. Choices are: auth_token, auth_token_set, contact, dob, email, employee_code, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, user_permissions I tried to remove the migrations file and re-run the migrations, but no use. Then I deleted the App completely and configured each and everything from scratch. Yet the same error. Here is the full Error stack models.py from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, AbstractUser from django.utils.translation import gettext_lazy as _ class AccountManager(BaseUserManager): def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) def create_user(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) if not email: raise ValueError(_('Enter the email before proceeding')) email = self.normalize_email(email) user = self.model(email=email, password=password, **extra_fields) user.set_password(password) user.save() return … -
How to deploy a Vue.js App + Django Database to Heroku?
I created a Vue.js App with a Django Database. The Vue.js App is running with router and webpack-bundle. I want to deploy that App to Heroku, so I can access it from there. When I separately deploy them to Heroku it works, but not together in one combined app. My folder structure looks like that: core/ ├─ views.py ├─ __init__.py frontend/ ├─ node_modules/ ├─ public/ │ ├─ favicon.ico │ ├─ index.html ├─ src/ │ ├─ views/ │ ├─ App.vue │ ├─ main.js │ ├─ router.js ├─ .gitignore ├─ package.json ├─ README.md ├─ vue.config.js ├─ webpack-stats.json my-app-products/ ├─ api/ ├─ admin.py ├─ apps.py ├─ models.py ├─ views.py my-app-shop/ ├─ asgi.py ├─ settings.py ├─ urls.py ├─ wsgi.py ├─ __init__.py The main problem I encounter is, that the vue app is in a subdirectory and I don't know how to deploy two apps in Heroku. If that is even possible, to deploy two apps in one project. I have knowledge on using git and on changing the heroku buildpack. Thanks in advance -
How dowload image from url to this custom ImageField(JsonField) Django
I have custom model_field in Project. I upload an excel file with data where I store links to photos(of this type https://url?token).I perform excel processing using pandas, and save data to the database via the serializer. How can I open the link and get the image to write it to this field of the model. This custom field in model_field.py class PsImageModelFieldBase(JSONField): def __init__(self, ps_image_class, **kwargs): assert issubclass(ps_image_class, BasePsImage) self.ps_image_class = ps_image_class super().__init__(**kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() args.append(self.ps_image_class) return name, path, args, kwargs def create_object(self, kwargs): if kwargs is None: return None try: if isinstance(kwargs, BasePsImage): return kwargs return self.ps_image_class(**kwargs) except TypeError: return kwargs class PsImageModelField(PsImageModelFieldBase): def get_prep_value(self, value): if value is not None and isinstance(value, (dict, list, BasePsImage)): value = self.create_object(value).as_json return super().get_prep_value(value) def from_db_value(self, value, expression, connection): return self.create_object(value) image.py import os import re from django.conf import settings from common.utils import camel_to_snake from photoservice.service import PhotoService class InvalidFormatError(Exception): pass _default_photo_service = PhotoService() def _validate_format(format_, format_regexes): is_valid = any(regex.match(format_) for regex in format_regexes) return is_valid def _validate_versions(class_name, versions, format_regexes): for fname, format_ in versions.items(): if not _validate_format(format_, format_regexes): raise InvalidFormatError(f'{class_name}: version="{fname}": "{format_}" is invalid') class PsImageMeta(type): """ Metaclass for default formats validation. """ def __new__(mcs, …