Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IntegrityError in djnago
Help I m getting IntegrityError can't find a solution to this error please help or show me how to fix this. The error is showing as follows: (1048, "Column 'targetDefn_id' cannot be null") this error is showing when I post data. This is my views.py in Post method I m getting this error: def setTarget(request): if request.method == 'POST': data=JSONParser().parse(request) print(data) serial=TargetSerializers(data=data) print(serial) if serial.is_valid(): serial.save() print("done") return JsonResponse(serial.data,status=status.HTTP_200_OK,safe=False) return JsonResponse(serial.errors, status=status.HTTP_400_BAD_REQUEST) This is my Serializer.py as follows: class TargetSerializers(serializers.ModelSerializer): targetDefn=serializers.SerializerMethodField() roleId=serializers.SerializerMethodField() empId=serializers.SerializerMethodField() class Meta: model = Target fields = ( 'id', 'targetDefn', 'roleId', 'empId', 'startDate', 'endDate', 'value' ) def get_targetDefn(self,obj): trgt = TargetDefination.objects.get(id=obj.targetDefn_id) serial = TargetDefinationSerializers(trgt) return serial.data def get_empId(self,obj): emp= Employee.objects.get(id=obj.empId_id) serial= OnlyEmployeeSerializers(emp) return serial.data def get_roleId(self,obj): role=Role.objects.get(id=obj.roleId_id) serial=RoleSerializers(role) return serial.data This is models.py as follows: class Target(models.Model): targetDefn=models.ForeignKey(TargetDefination,on_delete=models.CASCADE) roleId=models.ForeignKey(Role,on_delete=models.CASCADE) empId=models.ForeignKey(Employee,on_delete=models.CASCADE) startDate= models.DateField(default=datetime.date.today) endDate= models.DateField(null=True,blank=True) value=models.PositiveIntegerField(default=0) def __str__(self): return str(self.empId) + ' ' +str(self.targetDefn) -
Django Linking 2 tables through a foreign Key
i'm starting with django, and i'm trying to make an app that links orders to clients, for the user to be able to click a client and see wich orders that client have made. The issue is, every single tutorial uses either the command prompt or the admin screen to do those links manually, and i need them automatically from the code. This code is the one that i'm using for the Orden form. I get 2 errors, the first one is an 404 error ordenfill page not found, this after i click the guardar button, i suppose this is happening because after i click the guardar button, the form is not valid and is trying to reach an ordenfill url without the "nombre" parameter, but i'm not sure. If i remove the nombre parameter from the view and the url, then i dont know how to get that name and link the form to it, with this the 404 error stops but i never get a valid form because the system tells me the client field is needed. This ones are the models class Cliente(models.Model): nombre = models.CharField(max_length=100) email = models.EmailField(max_length=50) direccion = models.CharField(max_length=100, default='direccion') class Meta: db_table = … -
How to uniquely identify a model instance in django
I have program that keeps book records for different schools I have a Student model that enables each school to upload the students from an excel. I however get an error because already there are two schools each having form 1 form 2 and form 3. It returns MultipleObjectsReturned error. Setting the filed as unique also does not allow other schools to create the same klass. How is it that I can be able to uniquely identify every instannce ok Klass model so it returns no error. get() returned more than one Klass -- it returned 2! class ImportStudentsResource(resources.ModelResource): school = fields.Field(attribute = 'school',column_name='school', widget=ForeignKeyWidget(School, 'name')) klass = fields.Field(attribute = 'klass',column_name='class', widget=ForeignKeyWidget(Klass, 'name')) stream = fields.Field(attribute = 'stream',column_name='stream', widget=ForeignKeyWidget(Stream, 'name')) class Meta: model = Student fields = ('school','student_id','name','year','klass','stream') import_id_fields = ('student_id',) import_order = ('school','student_id','name','year','klass','stream') class uploadStudents(LoginRequiredMixin,View): context = {} def get(self,request): form = UploadStudentsForm() self.context['form'] = form return render(request,'libman/upload_student.html',self.context) def post(self, request): form = UploadStudentsForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() resource = ImportStudentsResource() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) if result.has_validation_errors() or result.has_errors(): messages.success(request,f'Errors experienced during import.') print("error", result.invalid_rows) … -
How to verify users email with token generator link for signup in django webapp
I am doing a web app in Django. I hardly tried to create a TokenGenerator for verifying the user's email to activate the user's account coming to the problem, 1) how to send the verification email to the user account while signup. while signup, users can receive a verification link email with a token generator 2) the user has to input the password at the time of account signup 3) After verifying the email user can log in to the respective page via their mail id and password 4) while login it should check whether an email is present in the DB (DB will be updated with user emails ) -
how to store variables in django cache db
i am making a cache db using the django cache module i configured it in my settings.py like this CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_cache_table', } } so in my something.py file example def function(): log=cache['default'] log["cal"]+=1 can i do this so that a variable like cal would be formed and it would increase every time i call that function -
run django related script in crontab
Hi in my local python interpreter I run ./manage.py shell < slack_application/slack_notifications.py in my activated venv and everything works... How can I do the same via a crontab that should work on my ubuntu server? I am trying: cd Django django_env/bin/activate ./manage.py shell < slack_application/slack_notifications.py) Any ideas? Thank you very much. -
Refresh UUID on model object save
so I have a model and I am using a UUID field. I just simply want to change the UUID(refresh the UUID) to a new UUID every time a model object is saved. import uuid from django.db import models class MyUUIDModel(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True) # other fields def save(self, *args, **kwargs): //refresh the uuid. what do i do here? super(MyUUIDModel, self).save(*args, **kwargs) -
How to show name of the foreign key field instead of its id?
I need to show the names of 'user_permissions' instead of their id's. Serializers.py : class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name', 'username', 'email','password','is_active', 'date_joined', 'groups', 'user_permissions') extra_kwargs = {'username' : {'read_only': True},'password': {'write_only': True}, 'is_active': {'read_only': True}, 'date_joined': {'read_only': True}, 'groups':{ 'read_only' : True} , 'user_permissions':{ 'read_only' : True} } Views.py: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer -
Iterate over a list of django forms, give each form its own div in template
I'm working on an app that lets restaurants/venues update their current state (i.e occupancy, or music type) I have a model called State and a ModelForm that corresponds. In my python view I've created a list of forms. Each form field is set with the existing value of a particular venue. I'm rendering a page where I'd like a user to see all of the venues they have, in its own div, that has the form from that list that corresponds. This way if they only want to update one field of a particular venue then they only have to set one field, instead of having a blank form and resetting everything. Currently all the preferences load correctly. However each Venue is showing the form and preferences for EVERY venue in its particular div. I can't workout out how to iterate. I've tried hardcoding setForms[0] and it throws an error pictures below show webpage with 4 venues (each in its own row), each venue div have all four forms models.py: class Venue(models.Model): owner = models.ForeignKey("User", on_delete=models.CASCADE) name = models.TextField(blank=False) rawAddress = models.TextField(blank=False) area = models.TextField(blank=True) locationPoint = models.PointField(srid=4326) objects = GeoManager() class State(models.Model): venue = models.ForeignKey("Venue", on_delete=models.CASCADE, related_name="states") venueType = … -
Django Rest framework GET request on db without related model
Let's say that we have a database with existing data, the data is updated from a bash script and there is no related model on Django for that. Which is the best way to create an endpoint on Django to be able to perform a GET request so to retrieve the data? What I mean is, that if there was a model we could use something like: class ModelList(generics.ListCreateAPIView): queryset = Model.objects.first() serializer_class = ModelSerializer The workaround that I tried was to create an APIView and inside that APIView to do something like this: class RetrieveData(APIView): def get(self, request): conn = None try: conn = psycopg2.connect(host=..., database=..., user=..., password=..., port=...) cur = conn.cursor() cur.execute(f'Select * from ....') fetched_data = cur.fetchone() cur.close() res_list = [x for x in fetched_data] json_res_data = {"id": res_list[0], "date": res_list[1], "data": res_list[2]} return Response({"data": json_res_data) except Exception as e: return Response({"error": 'Error'}) finally: if conn is not None: conn.close() Although I do not believe that this is a good solution, also is a bit slow ~ 2 sec per request. Apart from that, if for example, many Get requests are made at the same time isn't that gonna create a problem on the DB instance, e.g … -
checkboxes form from database and initials
Assume that we have some languages for our dictionary (which is a model and its name is Lang), English, 2. Spanish, 3. German These languages can be increased or decreased later on by the admin. I want the user to choose between them and save them in the User model. But a user previously chose some or all of them. So, How can I build a form that has the form grabbing the languages from the database and it has also the initial value of True for the chosen languages by the user, in the checkboxes? -
Is there any way to make any way to make a model abstract without loss of data?
Lets say I have 2 models such that: class Parent(models.Model): ... class Child(Parent): ... Is there any way to make parent abstract without loss of existing data, given that the parent class has never been directly used. Other answers have suggested using dumpdata and loaddata to preserve data but I was wondering if there was a better way to do so. -
Django, model filter and order by other foreignkey model
model1: class Tag(models.Model): text = models.CharField(max_length=255, null=True, blank=True, unique=True) model2: class TagConnect(models.Model): tag = models.ForeignKey("category.Tag", on_delete=models.CASCADE, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) I want to get top 5 Tag object by count of TagConnect object that has created in recent 24 hours. The more TagConnect object exists, the tag is more likely on high priority. If tag "rabbit" has 2 TagConnect in 24 hours and "horse" has 10 TagConnect but those are not in 24 hours, "rabbit" has more high priority. Maybe it will be like.. Tag.objects.order_by(tag_connect_in_24hours)[:5] How to do this? -
Django Pagedown not rendering correctly in template
I am trying to implement django-pagedown and it works inside the django-admin, but it doesn't render correctly inside a template, this is what I have: new_post_form.py from django import forms from pagedown.widgets import PagedownWidget from .models import Post class NewPostForm(forms.ModelForm): description = forms.CharField(widget=PagedownWidget()) class Meta: model = Post fields = ["description"] views.py def home(request): context = {'post_form':NewPostForm} return render(request, 'pages/index.html', context) index.html <head> {{ post_form.media }} </head> postform.html <form> {{ post_form }} </form> This is what I get: <form> <div class="wmd-wrapper"> <div class="wmd-panel"> <div id="wmd-button-bar-id_description" class="wmd-button-bar"></div> <textarea name="description" cols="40" rows="10" class="wmd-input" required="" id="wmd-input-id_description"></textarea> </div> <div id="wmd-preview-id_description" class="wmd-preview"></div> </div> </form> Thank you for any suggestions -
Django rest framework get request on db with no related model
I am a bit confused. Let's say that we have a database with existing data, the data is updated from a bash script and there is no related model on Django for that. Which is the best way to create an endpoint on Django to be able to perform a GET request so to retrieve these data? What I mean is, that if there was a model we could use something like: class ModelList(generics.ListCreateAPIView): queryset = Model.objects.all() serializer_class = ModelSerializer The workaround that I tried was to create an APIView and inside that APIView to do something like this: class RetrieveData(APIView): def get(self, request): conn = None try: conn = psycopg2.connect(host=..., database=..., user=..., password=..., port=...) cur = conn.cursor() cur.execute(f'Select * from ....') fetched_data = cur.fetchone() cur.close() res_list = [x for x in fetched_data] json_res_data = {"id": res_list[0], "date": res_list[1], "data": res_list[2]} return Response({"data": json_res_data) except Exception as e: return Response({"error": 'Error'}) finally: if conn is not None: conn.close() Although I do not believe that this is a good solution, also is a bit slow ~ 2 sec per request. Apart from that, if for example, many Get requests are made at the same time isn't that gonna create a problem … -
Django models filter query not recognising field
I am working on a Django project, filter query function is not working as expected I imported the model, did migration I don't understand where the code is wrong, it is not able to recognize the field (rating) Model I created My code in views: ( object.all() is working properly but the filter is not working) My error : ( rating not defined) (basically I tried all fields it shows all not defined) Thank you for help -
How to add/exclude fields to a form that extends another form
Example forms.py: class UserCreationForm(forms.ModelForm): class Meta: model = User fields = ('email', 'role', 'first_name', 'last_name', 'is_staff') class AnotherUserCreationForm(UserCreationForm): #??? Example models.py: ROLE = [ ("NU", "Normal User"), ("AU", "Abnormal User"), ] class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), max_length=50, unique=True) first_name = models.CharField(_('first name'), max_length=50, blank=True) last_name = models.CharField(_('last name'), max_length=50, blank=True) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(_('staff status'), default=False) date_of_birth = models.DateField(blank=True) role = models.CharField(_('role'), max_length=2, choices=ROLE, blank=True) So I want to add date_of_birth to AnotherUserCreationForm and at the same time, I want to exclude role and is_staff in AnotherUserCreationForm. How do I manipulate it? Will it be done in the Meta class or do i manipulate it in the def __init__(self, *args, **kwargs) of AnotherUserCreationForm? -
Django sending email with TLS doesn't seem to be working
The emails I send are going through, but do not seem to be encrypted through TLS even though I have it configured to do so. I tried switching port and using SSL, but that also did not work. Settings.py #FOR EMAIL THING PRODUCTION EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = '***************' EMAIL_USE_TLS = True admin.py (emails are sent in admin page) def send_email(self, request, queryset): updated = 0 for obj in queryset: updated +=1 #makes magic link from obj link = get_query_string(obj) subject, from_email, to = 'Pre-appointment Form', 'mail@myserver.com', [obj.email] html_message = render_to_string('mail_template.html', {'link': link}) plain_message = strip_tags(html_message) msg = EmailMultiAlternatives(subject, plain_message, from_email, to) msg.attach_alternative(html_message, "text/html") msg.send() # update message on how many emails were sent self.message_user(request, ngettext( '%d email was successfully sent.', '%d emails were successfully sent.', updated, ) % updated, messages.SUCCESS) -
Did you rename table_name.pid to table.id (a BigAutoField)? [y/N]
I have been running a Django app for last couple of weeks with no issues. However I started to see the above warning message out of no where when I tried to make migration (renaming invoice_date to order_date). When I closely look at the migration files, I see that the initial migration file auto created the pid column. But when I describe the tables in dev (sqlite3) the column name is in fact id. Just to confirm I did not attempt to rename the column name from pid to id. So I can't get my head around as to what is going on. If Django auto creates a column, it should manage the columns forever. Any intentional or unintentional changes to auto created columns should be blocked by Django. Below are the module verion I am using. Django==3.2.2 whitenoise==5.0 pandas==0.25.3 Detailed migration log: (venv) [prj(master)]$python manage.py makemigrations Did you rename packaging.pid to packaging.id (a BigAutoField)? [y/N] n Did you rename product.pid to product.id (a BigAutoField)? [y/N] n Did you rename purchase.pid to purchase.id (a BigAutoField)? [y/N] n Did you rename sale.pid to sale.id (a BigAutoField)? [y/N] n Did you rename saleschannel.pid to saleschannel.id (a BigAutoField)? [y/N] n Did you rename … -
django - Muliple choice filtering on multiple fields using defined choices
I am trying to filter through a model with the choices defined before the filter. store_choices = ( ('harveynichols', 'Harvey Nichols'), ('houseoffraser', 'House of Fraser'), ('selfridges', 'Selfridges'), ('lookfantastic', 'LOOKFANTASTIC'), ('superdrug', 'Superdrug'), ('boots', 'Boots'), ('allbeauty', 'allbeauty'), ('asos', 'asos'), ) class ProductFilter(django_filters.FilterSet): store = django_filters.MultipleChoiceFilter(choices=store_choices) brand = django_filters.MultipleChoiceFilter(choices=brand_choices) price = django_filters.RangeFilter() class Meta: model = Product fields = ['store', 'brand', 'price'] def store_checks(self, queryset, name, store_choices): return Product.objects.filter( Q(store__icontains=store_choices) | Q(storehn__icontains=store_choices) | Q(storehof__icontains=store_choices) | Q( storesf__icontains=store_choices) | Q(storelf__icontains=store_choices) | Q(storesd__icontains=store_choices) | Q(storeboots__icontains=store_choices) | Q(storeab__icontains=store_choices) | Q(storea__icontains=store_choices) ) This does not work and returns no products, I am not sure what variable to use instead of store_choices with the Q(XXX__icontains = ). Any help would be appreciated -
How to calculate percentage in python and django
Am writing a simple program to allow user to get in return 8 percent of any amount they invest in the period of ten days. The user balance in ten days will equal to Eight percent of any amount he/she invest and the percentage balance will be return into the user balance after ten days. Look at my code below and help me. Models.py class Profile(models.Model): user = models.ForeignKey(UserModel, on_delete=models.CASCADE) balance = models.DecimalField(default=Decimal(0),max_digits=24,decimal_places=4) class Investment(FieldValidationMixin, models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) fixed_price = models.DecimalField(max_digits=7, decimal_places=2, nulll=True, blank=True) percentageee = models.DecimalField(max_digits=3, decimal_places=0, nulll=True, blank=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return _("{0}: (#{1} {2}%, ${3})".format(self.__class__.__name__, self.amount, self.percentage, self.fixed_price) ) I want to fetch the percentage of the user investment amount here Views.py def get_percentage(self): pef_of_amount = Investment.objects.filter(amount=self.amount).annotate(percentageee=Sum('amount')) return '{:%}'.format(amount.percentageee / 8) def percentile(self, days=10): percent=Investment.objects.filter(self.amount*self.percentage)/100 in days return percentile #get the percentage balance of the amount invested after ten days def get_current_balance(self,percentile): total_expenses = Profile.objects.all().aggregate(Sum('balance')).annonate(percentile) return get_current_balance -
How to return multiple lists with a single get request?
I want to write a GET request for my Django app to get three lists. I want to apply a filter to my database and return them in different lists in one response. These are the three lists that I want, and I want to filter them with {"to do," "in progress," "Done"}. I don't know is there a way to return multiple lists in one response? or I should write different APIs for every one of them Many thanks. -
How to get Object resource URL after pre-signed post upload?
I am using python to create a pre-signed post URL to upload images into s3. After the upload, I need to save the Object resource URL into the database. def create_presigned_post(request): if request.method == 'POST': bucket_name = 'mybucket' object_name = request.data.get('file_name', 'TEST') fields = { "key": f'{uuid.uuid4()}_{object_name.replace(" ", "_")}' } # key = a918e6b8-b0f0-4067-95e4-82ade3b138c2_myfilename.jpg conditions = request.data.get('conditions', None) expiration = request.data.get('expiration', 3600) try: response = s3_client.generate_presigned_post(bucket_name, object_name, Fields=fields, Conditions=conditions, ExpiresIn=expiration) except ClientError as e: logging.error(e) return None return Response({"message": "Got some data!", "data": response}) return Response({"message": "Hello, world! If you need pre-signed POST URL, make a POST request."}) However, I was hoping the dictionary key in keys of fields dictionary will be the key. And I would be able to get the object URL. For example here: https://mybucket.s3-region.amazonaws.com/myfilename.jpg I thought the key (a918e6b8-b0f0-4067-95e4-82ade3b138c2_myfilename.jpg) that I specified in the fields key-value pairs would be used to construct the Object's resource URL. But instead it is the filename. Also, even in the response that I get from create_presigned_post, the key is the filename, instead of the actual key that I specified in the fields value. How would I get the Object's URL so that I can save it into the database? -
how join 3 table in Django Python
This is my first class class dot_bay(models.Model): ma_dot_bay = models.CharField(primary_key=True,max_length=255, default=uuid.uuid4, editable=False) ten_dot_bay = models.CharField(max_length=255, default="") ngay_bay = models.DateTimeField()``` This is my second class class video(models.Model): ma_video = models.CharField(primary_key=True, max_length=255, default=uuid.uuid4, editable=False) ma_dot_bay = models.ForeignKey(dot_bay, on_delete=models.CASCADE, related_name='dot_bay_video') video_path = models.TextField() detected_path = models.TextField() ngay_upload = models.TextField() And my third class class hinh_anh(models.Model): ma_hinh_anh = models.CharField(primary_key=True, max_length=255, default=uuid.uuid4, editable=False) ma_video = models.ForeignKey(video, on_delete=models.CASCADE, related_name='video_hinh_anh') image_base64 = models.TextField() I try this in my Serializer in my project to display result of 2 join table dot_bay and video like that class DotBayModelSerializer(serializers.ModelSerializer): class Meta: model = dot_bay fields = ("ma_dot_bay", "ten_dot_bay", "ngay_bay", "dot_bay_video") depth = 1 And get the result like that [ { "ma_dot_bay": "db0001", "ten_dot_bay": "Đợt bay", "ngay_bay": "2021-05-14T15:30:27Z", "dot_bay_video": [ { "ma_video": "vd0001", "video_path": "1", "detected_path": "1", "ngay_upload": "1", "ma_dot_bay": "db0001" }, { "ma_video": "vd0002", "video_path": "1", "detected_path": "1", "ngay_upload": "1", "ma_dot_bay": "db0001" } ] }, { "ma_dot_bay": "db0002", "ten_dot_bay": "Đợt bay", "ngay_bay": "2021-05-14T15:31:07Z", "dot_bay_video": [ { "ma_video": "vd0003", "video_path": "1", "detected_path": "1", "ngay_upload": "1", "ma_dot_bay": "db0002" }, { "ma_video": "vd0004", "video_path": "11", "detected_path": "1", "ngay_upload": "1", "ma_dot_bay": "db0002" } ] } ] that's what I expected But now I want to join 3 table, display like that, [ { … -
Django formset with multiple choicefields(select) which have same datasource
I need a design recommendation about Django formset with multiple choicefields(select) which have same datasource. in my project I have simply: ''' Models class Event(models.Model): name= models.Charfield() class Schedule(models.Model): day = models.CharField(max_length=10) hour = models.CharField(max_length=10) event = models.ForeignKey(Event, on_delete=models.DO_NOTHING, related_name="event") Forms class FormSchedule(forms.ModelForm): class Meta: model = Schedule fields = 'all' views def schedule(request): if request.method == 'POST': ..... else: event_queryset = Event.objects.all() choice = maketuple(event_queryset) form_size = 24 * 7 # weekly schedule formset_ = formset_factory( FormSchedule, extra=168) formset = formset_() for form in formset: form.fields['event'].choices = choice return render(request, 'core/schedule.html','formset': formset}) ''' it works in runitme without error. I have html page with 168 selects and each select has 50 options. the problem is It takes more than 15 seconds loading page. is there any way to optimize this process thanks a lot,