Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cant save forms to models django
i cant save my forms to a models into my database the code work smoothly no errors but if i check in django admin its not save to my database model can you help me here my code : forms.py class InstagramUsernameForm(forms.ModelForm): class Meta: model = InstagramUsername fields = ('nama_orang','username','nama_depan') nama_orang = forms.CharField(max_length=20) username = forms.ModelChoiceField(queryset=Instagram.objects.values_list("username", flat=True)) nama_depan = forms.ModelChoiceField(queryset=Instagram.objects.values_list("nama_depan", flat=True)) models.py from django.db import models # Create your models here. class Instagram(models.Model): nama_depan = models.CharField(max_length=100,blank=True,null=True) nama_belakang = models.CharField(max_length=100) username = models.CharField(max_length=100) def __str__(self): return self.username class InstagramUsername(models.Model): nama_orang = models.CharField(max_length=20) username = models.CharField(max_length=20) nama_depan = models.CharField(max_length=100,default='') def __str__(self): return self.nama_orang views.py def create2(request): akun_form = InstagramUsernameForm(request.POST or None) if request.method == 'POST': if akun_form.is_valid(): akun_form.save() return redirect('sosmed:awe') else: print(akun_form.errors) context = { "akun_form":akun_form, } return render(request,"sosmed/awe.html",context) awe.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>awe</title> </head> <body> <form method="post"> {% csrf_token %} <h1>awe</h1> <table> {{ akun_form.as_table }} </table> <button type="submit">Create</button> </form> </body> </html> cant save forms to django models -
While creating dynamic url I am getting a Reverse for 'dashboard_group' with arguments error
urls.py urlpatterns = [ path('processes/', views.processes, name="dashboard"), path('processes/<uuid:u_id>/', views.groups, name="dashboard_group") ] views.py def processes(request): return render(request, 'processes/index.html') def groups(request, u_id): return render(request, 'create_instance/index.html') The above code gives me following error - Reverse for 'dashboard_group' with arguments '('a21713b0ec29416c8fb27d4f339eabb8',)' not found. 1 pattern(s) tried: ['processes\/(?P[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/$'] -
django rest framework get request in serializer create method
I'm a student studying django rest framework I tried to upload multiple file with form-data this is model class Post(models.Model): text = models.CharField(max_length=5000) owner = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Image(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.FileField(blank=True) And views class AddPost(APIView): serializer_class = PostSerializer def post(self, request, format=None): serializer = PostSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return JsonResponse({'status':status.HTTP_200_OK, 'message':"sucess", 'data':""}) serializers class FileSerializer(serializers.ModelSerializer): class Meta: model = Image fields = '__all__' class PostSerializer(serializers.ModelSerializer): images = FileSerializer(source='image_set', many=True, read_only=True) class Meta: model = Post fields = ('id', 'text', 'owner', 'created_at', 'images') def create(self, validated_data): images_data = self.context.get('request').request.FILES images_data = self.context.get('request').request.FILES post = Post.objects.create(text=validated_data.get('text'),owner=validated_data.get('owner')) for image_data in images_data.values(): Image.objects.create(post=post, image=image_data) return post when i send request like this in postman enter image description here error occurs and this is error message images_data = self.context.get('request').request.FILES AttributeError: 'NoneType' object has no attribute 'request' i already saw this link https://codeday.me/en/qa/20190306/12057.html thanks for your help -
does not work sympy-gamma on digital ocean server
I am download github code for sympy-gamma form here:- https://github.com/sympy/sympy and put on my digital ocean server. It is run the code but the step by step solution does not display. is any external tool is required for display step by step solution on server? can any one please help me! -
How do I cancel the option url after the link?
debug=true local static enter image description here debug=false static server enter image description here how do i cancel ?_=2.1this string? -
Celery beat processed messages not removed from ready state
I have Celery beat defined as: @periodic_task(run_every=(crontab(minute='*/15')), name='threshold_monitor', ignore_result=True, queue='default', options={'queue': 'default'}) def threshold_monitor(): #Threshold check login Celery is run through supervisord as: celery -A ProjectName beat --loglevel=info The task is well executed every 15 minutes but it is not removed from the celery queue as expected. The number keeps growing in RabbitMq. Is this the expected behavior? If not, how do I fix it. Other celery settings: CELERY_RESULT_BACKEND = 'rpc' CELERY_ACKS_LATE = True CELERY_IGNORE_RESULT = True CELERY_TASK_IGNORE_RESULT = True CELERYD_PREFETCH_MULTIPLIER = 1 CELERY_TASK_DEFAULT_QUEUE = 'default' CELERY_TASK_ALWAYS_EAGER = False CELERYD_TASK_TIME_LIMIT = 60 RabbitMQ queue screenshots: Note the default queue items are executed and released, but celery keeps growing. -
terjadi expected an indented block
from django.db import models from django.contrib.auth import User Create your models here. class UserProfileInfo(model.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) def str(self): return self.user.username user = models.OneToOneField(User,on_delete=models.CASCADE) ^ IndentationError: expected an indented block -
How to implement JWT authentication in web app after a registered user logs in?
I am new to Django and I want to implement JWT authentication in order to view an API data for the currently logged-in user, only. Can someone please give me a hint on how to structure the implementation of JWT in Django (version 2.1)? -
Nginx: how to reroute subdomains to Django?
How to catch and reroute subdomains internally in Nginx to Django's URL dispatcher? api.project.org/ -> /api/ www.project.org/ -> /www/ project.org/ -> /www/ I want to get something like this: location api.project.org/ { uwsgi_pass 127.0.0.1:8080/api/; } -
How to get all related data using django signal post_save and save it to another table
I just want that if the admin insert the Course(ABM) and Education Level (Grade 11) and Section(Chronicles) it will get all related data in subjectsectionteacher(second picture) and it will automatic save to student enrolled subject(third picture) my problem is only one data save. this is my code in models.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True,null=True) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, **kwargs): teachers = SubjectSectionTeacher.objects.all().filter(Sections=instance.Section,Education_Levels=instance.Education_Levels) if created and teachers.exists(): StudentsEnrolledSubject.objects.update_or_create( # This should be the instance not instance.Student_Users Students_Enrollment_Records=instance, # The below is also not an instance of SubjectSectionTeacher Subject_Section_Teacher=teachers.first()) I hope the title and the picture is enough to understand what im trying to say if not, im sorry! UPDATE this … -
Django CheckboxSelectMultiple allow none
I need some help, I'm using a forms.ModelMultipleChoiceField to represent a ManyToManyField, rendered as a widget=forms.CheckboxSelectMultiple. All work perfect but the problem come when none checkbox was selected, it raises a validationError when ask form.is_valid(). I need Select None, One, Many or All. It is any way to allow blank or empty? Thanks!! -
How to create custom search Mixin?
I have a ListView which utilizes the q GET parameter for a search box. The problem is that I am not following the DRY principle as I have other search boxes which are similar. Therefore I would like to make a custom SearchMixin to handle the search queries. My ListView previously looked like this: class MemoListView(LoginRequiredMixin, ListView): """ Display a list of memos. **Context** ``Memo`` An instance of :model:`memos.Memo` **Template:** :template:`memos/memos.html` """ model = Memo template_name = 'memos/memos.html' context_object_name = 'memos' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['memo_list'] = Memo.objects.all() return context def get_ordering(self): ordering = self.request.GET.get('ordering', '-date_time') return ordering def get_queryset(self): query = self.request.GET.get('q') user_casino = self.request.user.casino user_emp_type = self.request.user.employee_type ordering = self.get_ordering() if query: object_list = Memo.objects.filter( casino=user_casino).filter( receiver=user_emp_type).filter( Q(title__icontains=query) | Q(content__icontains=query ) ) else: object_list = Memo.objects.filter( casino=user_casino).filter( receiver=user_emp_type ) if ordering and isinstance(ordering, str): ordering = (ordering,) object_list = object_list.order_by(*ordering) return object_list I am trying to create the SearchMixin as such: class SearchMixin: def get_queryset(self): queryset = super(SearchMixin, self).get_queryset() query = self.request.GET.get('q') if query: print('yes') return queryset.filter(Q(title__icontains=query) | Q(content__icontains=query)) print('no') return queryset The problem is that the query is not hitting the SearchMixin when I add it to the MemoListView as such: class MemoListView(LoginRequiredMixin, SearchMixin, ListView): … -
How too make dropdown list from database django
guys i have problem about django forms when post to my database here my code : forms.py : class InstagramUsernameForm(forms.ModelForm): nama_orang = forms.CharField(max_length=20) username = forms.ModelChoiceField(queryset=Instagram.objects.all()) nama_depan = forms.ModelChoiceField(queryset=Instagram.objects.values_list("nama_depan")) class Meta: model = InstagramUsername fields = ('nama_orang','username','nama_depan') models.py : class Instagram(models.Model): nama_depan = models.CharField(max_length=100) nama_belakang = models.CharField(max_length=100) username = models.CharField(max_length=100) def __str__(self): return "{}".format(self.username) class InstagramUsername(models.Model): nama_orang = models.CharField(max_length=20) username = models.CharField(max_length=20) nama_depan = models.CharField(max_length=30) def __str__(self): return self.nama_orang this is my views.py: def create2(request): akun_form = InstagramUsernameForm(request.POST or None) if request.method == 'POST': if akun_form.is_valid(): akun_form.save() return redirect('sosmed:awe') context = { "akun_form":akun_form, } so the problem is when i deactivate "nama_depan" in forms.py its can save to models database when i activate it cant save to models database anyone know it ty ;D -
How could I show the data from mysql to a modal where it I could update it also?
Im a new to Django and i was trying to show the information/data from mysql to a Modal and on same time I can also update those data if possible. class User(models.Model): login_id = models.AutoField(primary_key=True) user_id = models.CharField(max_length=45, blank=True, null=True) employee = models.ForeignKey(Employee, models.DO_NOTHING, blank=True, null=True) password = models.CharField(max_length=45, blank=True, null=True) user_type = models.CharField(max_length=45, blank=True, null=True) class Meta: managed = False db_table = 'user' -
Django save all required documents
I have this code in my html <tr> <td colspan="2" style="text-align: center;"><h2 style="font-weight: bold;">Required Documents:</h2></td> </tr> {% for d in doc %} <tr> <td style="text-align: left;"> <input type="file" name="myfile" value="{{d.id}}" style="outline: none;" required/>{{d.Description}}</td> <td></td> </tr> {% endfor %} This is my code in views.py V_insert_data = StudentsEnrollmentRecord( Student_Users=studentname, Payment_Type=payment, Education_Levels=educationlevel,School_Year=schoolyear ) V_insert_data.save() insert_doc = StudentsSubmittedDocument( Students_Enrollment_Records = V_insert_data, Document = myfile ) insert_doc.save() \model class StudentsSubmittedDocument(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,blank=True,null=True) Document_Requirements = models.IntegerField(null=True,blank=True) Document = models.FileField(upload_to='files/%Y/%m/%d',null=True,blank=True) Remarks = models.CharField(max_length=500,blank=True,null=True) def __str__(self): suser = '{0.Students_Enrollment_Records}' return suser.format(self) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) How to save all in the database all the required documents that the user input? QUESTION UPDATED all documents that the students input, it will save in the database, in my case even the students input 4 documents only 1 documents save in the database -
How to create a similar to "setUp" method in unittest using pytest fixtures and django
I have the code below in my test files and trying to refactor it. I am new to pytest and i am trying to achieve the similar method setUp available with unittest to be able to retrieve the object created in the db to other function instead of repeating the codes. In this case I want to reuse month from test_setup to the other functions. test_models.py @pytest.mark.django_db class TestMonth: # def test_setup(self): # month = Month.objects.create(name="january", slug="january") # month.save() def test_month_model_save(self): month = Month.objects.create(name="january", slug="january") month.save() assert month.name == "january" assert month.name == month.slug def test_month_get_absolute_url(self, client): month = Month.objects.create(name="january", slug="january") month.save() response = client.get(reverse('core:month_detail', kwargs={'slug': month.slug})) assert response.status_code == 200 I would appreciate the help. -
Heroku config for a Django app that requires a Firebase JSON?
I have a Python Django app deployed on Heroku that uses Firebase through the drf-firebase-auth library (which I must use for a number of reasons). I know that configuration shouldn't be checked into version control, but I'm not sure how to avoid it in my case. The drf-firebase-auth library requires the Firebase credential JSON file to be saved in my code's directory structure. How can I pass this JSON essentially via Heroku environment variables without needing to commit the JSON file to my git repo (and push to Heroku), so that I can have a proper config setup for staging/production/etc? The drf-firebase-auth library instructs me to add this to my settings.py and also to save my very sensitive firebase.json file to my codebase: DRF_FIREBASE_AUTH = { 'FIREBASE_SERVICE_ACCOUNT_KEY': 'project/config/firebase.json' } The implementation within this 3rd party library looks a bit like this: import firebase_admin from drf_firebase_auth.settings import api_settings ... firebase_credentials = firebase_admin.credentials.Certificate( api_settings.FIREBASE_SERVICE_ACCOUNT_KEY ) firebase = firebase_admin.initialize_app(firebase_credentials) ... The problem is that I would like to avoid committing this Firebase JSON to git in order to deploy to Heroku. -
Proper way to run nameko service(s) inside a Django application?
If I have a vanilla Django REST (DRF) application and I would like to integrate a nameko service (specifically an event_handler event listening service), what's the best way to achieve this? I cannot simply nameko run a service if it's part of a Django application. I'm considering running the nameko service via a custom Django management command, but would I lose some of nameko's features, say, scalability? Eg. nameko maintains a pool of 10 workers per nameko run (if I remember correctly). -
How to get single filed value with aggregate from other model?
I need to divide two queries values from one model and group it by names from another model, but I can't understand how to connect it by foreign key and how I can divide different queries. Query that I need in SQL: Select m2.regionname,m2.indicatorname, round(CAST( m2.a2Value as float) / m1.a1Value,2) from( select r.name as regionname , ina.name as indicatorname, sum(a.value) as a1Value from Region as "r" left join city_region as "cr" on r.region_id = cr.region_id left join Office as "o" on cr.city_id = o.city_id left join Assets as "a" on o.office_id = a.office_id left join Indicators as "i" on a.indicator_id = i.indicator_id left join IndicatorNames as "ina" on i.indicator_name_id = ina.indicator__name_id where a.month between '01-01-2019' and '31-01-2019' group by r.name, ina.name ) m1 join ( select r.name as regionname , ina.name as indicatorname, sum(a.value) as a2Value from Region as "r" left join city_region as "cr" on r.region_id = cr.region_id left join Office as "o" on cr.city_id = o.city_id left join Assets as "a" on o.office_id = a.office_id left join Indicators as "i" on a.indicator_id = i.indicator_id left join IndicatorNames as "ina" on i.indicator_name_id = ina.indicator__name_id where a.month between '01-02-2019' and '27-02-2019' group by r.name, ina.name) m2 on m1.regionname = m2.regionname … -
Get all related data from model and save it to the another model using django signal
I just want that if the admin insert the Course(ABM) and Education Level (Grade 11) and Section(Chronicles) in table student enrollment record it will get all related data in subjectsectionteacher(second picture) and it will automatic save to student enrolled subject(third picture) my problem is only one data save. student enrollment record subjectsectionteacher This is what the result I want Result I want This is the result I get what I got result class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,null=True) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) -
i got the below error while calling the app
I have started making web development i got the below error even the app is given File "c:\users\vivek\appdata\local\programs\python\python37-32\Lib\pathlib.py", line 1168, in stat return self._accessor.stat(self) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' -
Django: Forbidden (CSRF cookie not set.), Why this is happening , and How to fix it
I wrote a test file to check if the URL works or not and it keeps printing Forbidden (CSRF cookie not set.) could please check what's the problem #post handler @csrf_exempt def post(self, request, *args, **kwargs): valid_json = is_json(request.body) if not valid_json: error_data = json.dumps({'message': 'Invalid data sent, please send using JSON format'}) return self.render_to_response(error_data, status=400) data = json.loads(request.body) form = SupervisorForm(data) if form.is_valid(): obj = form.save(commit=True) obj_data = obj.serialize() return self.render_to_response(obj_data, status=201) if form.errors: data_error = json.dumps(form.errors) return self.render_to_response(data_error, status=400) json_data = json.dumps({'message': 'Not Allowed'}) status_code = HTTP_400_BAD_REQUEST return self.render_to_response(json_data, status_code) def post(): data = { 'supervisor_name':'name', 'supervisor_phone': '76786875', 'supervisor_email': 'sdsds@sdsd.com', 'supervisor_image': 'path to local image', } json_data = json.dumps(data) json_loads = json.loads(json_data) print(type(json_data)) print(type(json_loads)) print(help(requests.put)) r = requests.put('http://127.0.0.1:8000/api', json = json.dumps(data)) return r.json() -
How to get data from a foreign key in django
I have a model as follows: class Products(models.Model): name=models.CharField(max_length=100) desc=models.CharField(max_length=1000) price=models.IntegerField() class Cart(models.Model): product=models.ForeignKey(Products,models.CASCADE) qty=models.IntegerField() I need to show all the items in the cart with their name and price. I have searched how to do this but don't understand. Please help. If you need more info I will give you. -
How can I implement text exchange between users
I have been working on a web app (lost and found platform) as a hobby project to learn django rest framework and angular. The idea is simple at the beginning, just let users post items they found and show list of found items. However, I don't know the best technology or approach to let the owner contact the original poster and claim the item. Any suggestions would be greatly appreciated. Thanks -
How to use django-storages to store and retrieve one field in my model
I use DRF for building our customer facing web app at my work. We have a Profile model which contains an ImageField which represent a User profile and his profile picture respectively. My job is to stop using FileSystem as a storage and switch to use s3 to store the images. I figured I would be able to do this using django-storages app. But I can't understand how to get django-storages to work with only one field in a model instead of using it as a default storage. I have tried using a FileField with storage set to storages.backends.s3boto3.S3Boto3Storage but am not able to save a file to s3. To summarize my question - How to configure django-storages as storage for only one field How to set and retrieve the field in my model. class Profile(models.Model): img = ImageField(upload_to=get_directory, default='img/generic_profile.jpg') name = CharField(max_length=256) new_s3_field = FileField(storage=S3Boto3Storage) profile = Profile() profile.new_s3_field = ContentFile('sample.jpg', open('sampel.jpg') # does not work File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1079, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 1111, in execute_sql for sql, params in self.as_sql(): File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 1064, in as_sql for obj in self.query.objs File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 1013, …