Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Blog post like feature
I want to make "like" feature for blog posts so that any user can like a post. I saw different approaches. In some they've made a model field "like", in some they've made a separate Like model and used the User and Post models as foreign keys in that. I'm also not sure about how to implement JavaScript in it. I mean how to call the methods or URLs. Hope you get it. It would be very helpful if anybody can explain how to do it. -
how to automatically generate a csv file when a user press the search button
i have a class base view which i want to automatically download a csv file but dont seem to know what am doing. here is my view view.py class ReportView(ListView): model = Pv # model been used template_name = 'pv/report.html' context_object_name = 'all_search_results' def get_queryset(self): result = super(ReportView, self).get_queryset() query = self.request.GET.get('search') # get the search critirial from the template today = datetime.datetime.now() if query: if query == "Withholding": postresult = Pv.objects.filter(Withholding_tax__gt =0.00,Date_recieved__year=today.year) elif query =="Non-Withholding": postresult = Pv.objects.filter(Withholding_tax__lte =0.00, Date_recieved__year=today.year) elif query =="Accountable-Impress": postresult = Pv.objects.filter(Acc_Impress__exact ='Yes',Date_recieved__year=today.year) elif query =="Non-Accountable-Impress": postresult = Pv.objects.filter(Acc_Impress__exact = 'No',Date_recieved__year=today.year) else: postresult = Pv.objects.all() result = postresult response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="report.csv"' today = datetime.datetime.now() data = result pvlist =data.filter(Date_recieved__year=today.year).order_by('IA_System_Code') writer = csv.writer(response) writer.writerow(['IA_System_Code','IA_code','Date_recieved','Pv_reference',\ 'Source_of_Funding','Cost_center','Payee',\ 'Description','Account_code','Gross_amount','Withholding_tax',\ 'Net_amount','Status','Acc_Impress','Date_returned',\ 'Type_of_accounts','Type_of_pv']) for pv in pvlist : writer.writerow([pv.IA_System_Code,pv.IA_code,pv.Date_recieved,\ pv.Pv_reference,pv.Source_of_Funding,pv.Cost_center,\ pv.Payee,pv.Description,pv.Account_code,pv.Gross_amount,\ pv.Withholding_tax,pv.Net_amount,pv.Status,pv.Acc_Impress,\ pv.Date_returned,pv.Type_of_accounts,pv.Type_of_pv]) else: result = None return result looks like i dont know what am doing. obviously my code is wrong . can any one here me out . what i want to achieve is the moment the person finish filtering , the csv file should generate automatically. -
Configuration of bokeh + channels integration
I’m using the bokeh django-embed example and have a few questions about what these lines are doing / how to access them by url: document(“shape_viewer”, views.shape_viewer_handler), document(“sea_surface_with_template”, views.sea_surface_handler_with_template) versus: autoload("sea_surface", views.sea_surface_handler) As best as I can tell, if you make the autoload route, then it uses the autoloadjs consumer to bundle up the bokeh app with autoload.js and then the websocket consumer later serves it to the websocket connection? I’m lost about the DocConsumer though - also, for testing purposes I attempted to remove the: 'websocket': AuthMiddlewareStack(URLRouter(patterns)) from routing.py, however for some reason it expects to find a ‘sea_surface/ws’ route - where is this specified? Is it possible to change it to for instance look for the websocket at ‘sea_surface/wasdf’? Lastly, is it possible to do other things with the websocket connection to a session / can I access it anywhere? Thanks for any help! -
Django - how i can add data in default auth_user table
I have "AddNewUserForm" form, for registration in index.html, and i need to add data from this form to default auth_user. How can i do that? -
Django aggregation function in Hstore field
I am using djagno postgres function from https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/ I need to use aggregation function in hstore field, but getting error... Here is my models.py def get_default_dict(): return {} class Post(models.Model): ................. extra_details = HStoreField(default=get_default_dict) class Meta: db_table = 'post' extra_details field save like {"abc":1}, {"abc":100}, {"abc":433} Now i have to get the post object where extra_details['abc'] value are highest ( ex. 433) I am tring to do like from django.db.models import Avg, Max Post.objects.filter(id__in=[1,2,3,4,5,..]).annotate(ab=Max('extra_details__abc')) getting error *** django.db.utils.ProgrammingError: function max(hstore) does not exist LINE 1: ......."statistics", MAX("post.. HINT: No function matches the given name and argument types. You might need to add explicit type casts. How can i use aggregate function in this situation? -
Django Select2Widget not getting styled properly with crispy forms
I'm using the django-select2 package to implement Searchable Select on a ForeignKey field. I was successful in getting the functionality to work by following the steps mentioned in the docs but I am having trouble with the styling. To render my form I use crispy-forms. All the other widgets get rendered properly except the Select2Widget. As can be seen in the above image, the height and width of the form element is not dynamic like other elements. HTML code generated: <div class=""> <select name="current_user" data-minimum-input-length="0" data-allow-clear="true" data-placeholder="" class="select2widget form-control django-select2" required id="id_current_user"> <option value=""></option> <option value="">---------</option> <option value="4" selected>Arpita</option> </select> </div> </div> <div id="div_id_device_admin" class="form-group"> <label for="id_device_admin" class=" requiredField"> Device admin<span class="asteriskField">*</span> </label> <div class=""> <select name="device_admin" data-minimum-input-length="0" data-allow-clear="true" data-placeholder="" class="select2widget form-control django-select2" required id="id_device_admin"> <option value=""></option> <option value="">---------</option> <option value="4" selected>Arpita</option> </select> </div> </div> This is how I set the widget in ModelForm. def __init__(self, *args, in_org, **kwargs): ... self.fields['current_user'].widget = Select2Widget() self.fields['current_user'].queryset = in_org.user_set.all() I feel this is mostly an issue with CSS styling and I am unable to figure out the issue. Any help would be greatly appreciated. -
i have logged in the student and have passed the queryset to the html page. it shows the following error in django
i'm working with django and mongodb with djongo as connector.i tried to login as student and if the login is successful the student details are displayed. but while doing so i got the following error. i kept the class company as abstract and used as embedded field in class student in my model.i haven't tried to access the company class directly also.still the problem persist. Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\sample\pro1\myapp\views.py", line 12, in login print(st) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 250, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 274, in __iter__ self._fetch_all() File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 72, in __iter__ for row in compiler.results_iter(results): File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1077, in apply_converters value = converter(value, expression, connection) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\djongo\models\fields.py", line 222, in from_db_value return self.to_python(value) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\djongo\models\fields.py", line 235, in to_python if isinstance(mdl_dict, self.model_container): TypeError: isinstance() arg 2 must be a type or tuple of types the html code looks like this : {% load static %} <html> <head> <style type="text/css"> body{ … -
Cant connect vnic through pyvomi
After a restore of a VMware VM through Veeam API, the Network adapter or vNic will not reconnect. When the VM gets a power off before the restore, the checkboxes for connect at powerOn get unchecked. My code runs tests afterwards, and because there is no connected vNic there is no IP address to check, thus my tests and with that the whole restoretask fail. This is my code. I tried to connect the Vnic before and after the poweron but both wont work. vo = VcenterAPIOperations(vdc_id=asset_obj.logical_switch.ive.datacenter.virtual_dc.id) power_on_result = vo.vm_power_on(vm_moid=asset_obj.moid, asset_id=asset_id) vnic_recon_result = vo.vm_reconnect_vnic(dvportgroup_moid=asset_obj.logical_switch.dvportgroup, vm_moid=asset_obj.moid) # Retrieve the VM hardware configuration and update the database vo.vm_update_hardware_config(asset_id=asset_id, task_id=task_id) return restore_result, power_on_result, vm_reconnect_vnic Where the vm_reconnect_vnic function is the following: def vm_reconnect_vnic(self, dvportgroup_moid, vm_moid): dvportgroup_obj = self._get_obj_by_moid(moid=dvportgroup_moid, folder_type='network', vim_type='dvportgroup') vm_obj = self._get_obj_by_moid(moid=vm_moid) for device in vm_obj.config.hardware.device: if isinstance(device, vim.vm.device.VirtualEthernetCard): nic_spec = vim.vm.device.VirtualDeviceSpec() nic_spec.operation = 'connect' nic_spec.device = device dvs_port_connection = vim.dvs.PortConnection() dvs_port_connection.portgroupKey = dvportgroup_obj.key dvs_port_connection.switchUuid = dvportgroup_obj.config.distributedVirtualSwitch.uuid nic_spec.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo() nic_spec.device.backing.port = dvs_port_connection vm_spec = vim.vm.ConfigSpec(deviceChange=[nic_spec]) task = vm_obj.ReconfigVM_Task(vm_spec) result = str(self.wait_for_task(task).info.state) return result Thanks in advance -
loop trough foreignKey objects in HTML with UpdateView
I am in process of writing UpdateView Class form , I am using inlineformset_factory to get ForignKey objects and its works , my issue is that i would like to iterate all ForignKey with HTML for displaying all its objects , and i am don't really know how to achieve it , since all objects i refer it , form. as declared in my forms.py so my question is someone could help me with given view and form how to, in HTML should i iterate my ForignKey objects Please advice Thanks my code is shown below my views.py Update view class TaskIdUpdateView(UpdateView): taskidformset = inlineformset_factory(MainTask,ChildTask, fields=('task_description','task_info','task_complete', 'sub_task','task_precent_complete','task_due_date','task_assign')) model = MainTask template_name = "taskid_update.html" form_class = TaskUpdateForm forms.py class form class TaskUpdateForm(ModelForm): TASK_STATUS_CHOICES = [ ('ST', 'STARTED'), ('NS', 'NOT STARTED'), ('IP', 'IN PROGRESS'), ('PA', 'PAUSED'), ('CO', 'COMPLETED'), ] INPUTֹTIMEֹFORMATS = ['%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', '%Y/%m/%d', # '10/25/2006' '%Y/%m/%d %H:%M', '%m/%d/%y', '%Y-%m-%d %H:%M:%S'] # '10/25/06' #Main Task objects task_title = forms.CharField(required=False, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Task Title'})) global_task_info = forms.CharField(required=True, widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Task Description'})) due_date = forms.DateTimeField(required=False, input_formats=INPUTֹTIMEֹFORMATS, widget=forms.DateTimeInput(attrs={ 'class': 'form-control', 'id': 'picker' })) global_task_assign = forms.ModelChoiceField(queryset= UserProfile.objects.all(), widget=forms.Select(attrs={'class':'form-control'} )) task_status = forms.ChoiceField(label='', choices=TASK_STATUS_CHOICES, widget=forms.Select(attrs={'class':'form-control'})) complete = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'type':'checkbox', 'class':'custom-control-input', 'id':'switchcomplete'})) overall_precent_complete = forms.IntegerField(widget=(forms.NumberInput(attrs={'type':'range', 'min':'0', 'max':'100', 'value':'50', … -
'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'
'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'. i am getting error on 'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'. any help, would be appreciated. 'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image' models.py class Product(models.Model): title = models.CharField(max_length=30) slug= models.SlugField(blank=True, null=True) sku = models.CharField(max_length=30) description = models.TextField(max_length=200, null=True, blank=True) instruction = models.TextField(max_length=200, null=True, blank=True) price = models.DecimalField(decimal_places=2, max_digits= 10,) discount_price= models.DecimalField(decimal_places=2, max_digits= 10, null=True, blank=True) brand = models.ForeignKey("Brand", null=True, blank=True, on_delete=models.CASCADE) waist = models.ForeignKey("Waist", null=True, blank=True, on_delete=models.CASCADE) occasion = models.ForeignKey("Occasion", null=True, blank=True, on_delete=models.CASCADE) style = models.ForeignKey("Style", null=True, blank=True, on_delete=models.CASCADE) neck = models.ForeignKey("Neck", null=True, blank=True, on_delete=models.CASCADE) fit = models.ForeignKey("Fit", null=True, blank=True, on_delete=models.CASCADE) pattern_type = models.ForeignKey("Pattern_Type", null=True, blank=True, on_delete=models.CASCADE) color = models.ForeignKey("Color", null=True, blank=True, on_delete=models.CASCADE) size = models.ManyToManyField("Size", null=True, blank=True) sleeve = models.ForeignKey("Sleeve_Length", null=True, blank=True, on_delete=models.CASCADE) material = models.ForeignKey("Material", null=True, blank=True, on_delete=models.CASCADE) category = models.ManyToManyField('Category', ) default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True, on_delete=models.CASCADE) created_on = models.DateTimeField(default=timezone.now) updated_on = models.DateTimeField(null=True, blank=True) status = models.BooleanField(default=True) class Meta: ordering = ["-id"] def __str__(self): #def __str__(self): return self.title def get_absolute_url(self): return reverse("product_detail", kwargs={"pk": self.pk}) def get_image_url(self): img = self.productimage_set.first() if img: return img.image.url return img #None def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(pre_save_post_receiver, sender=Product) def image_upload_to(instance, filename): title = instance.product.title slug = slugify(title) basename, file_extension … -
Django DATETIME_FORMAT incorrect (by one year) for specific dates
For a client I am storing event logs in a postgres database. Each event has a date that is stored as a timestamp with time zone in postgres. The date is automatically populated using Djangos' built in auto_now_add attribute in the model definition. In settings.py I have set the following: TIME_ZONE = 'UTC' USE_TZ = True DATETIME_FORMAT = 'd/m/o H:i:s' DATE_FORMAT = 'd/m/o' TIME_FORMAT = 'H:i:s' SHORT_DATE_FORMAT = 'd/m/o' SHORT_DATETIME_FORMAT = 'd/m/o H:i' I have lots of experience with this mechanism and it never caused problems until now. The client actually pointed out that there were a number of entries with a date lying in the future (impossible for event log). After checking the front-end as well as the admin I can verify that there are invalid dates e.g.(30/12/2020 and 31/12/2020) appearing (all invalid dates are in this range, other dates before and after are displaying correctly). When I check the database (Postgres) I can verify that the dates stored are actually both in 2019 having the following timestamp values: 2019-12-30 10:23:07.451674+00 and 2019-12-31 08:12:26.635693+00. The template in use in the frontend uses {{ log_item.date }} to display the date. What am I missing? Any hints appreciated. -
500 error message when i try and redirect to signup and login page in production
I get an error page when I try and access my signup or login pages in production, my login and signup pages work well in development so not sure it has anything to do with urls.py unless I'm missing something. Here is how my project is structured: home -->etc -->thegradientboostmvp ---->classroom >urls.py >models.py ---->django-app >urls.py >settings.py >wsgi.py ---->public >static >admin >css >img >vendor >second >third >fourth ---->static ------>admin ------>css ------>img ------>second >css >js >img ------>third >css >js >img ------>fourth >img >js >css ---->templates This is what I have in django-app/urls.py: from django.urls import include, path from classroom.views import classroom, students, teachers from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('classroom.urls')), path('accounts/', include('django.contrib.auth.urls')), path('accounts/signup/', classroom.SignUpView.as_view(), name='signup'), path('accounts/signup/student/', students.StudentSignUpView.as_view(), name='student_signup'), path('accounts/signup/teacher/', teachers.TeacherSignUpView.as_view(), name='teacher_signup'), ] and classroom/urls.py: urlpatterns = [ path('', classroom.home, name='home'), path('about', classroom.about, name='about'), path('courses', classroom.courses, name='courses'), path('course_details', classroom.course_details, name='course_details'), path('accounts/', include('django.contrib.auth.urls')), path('accounts/signup/', classroom.SignUpView.as_view(), name='signup'), path('accounts/signup/student/', students.StudentSignUpView.as_view(), name='student_signup'), path('accounts/signup/teacher/', teachers.TeacherSignUpView.as_view(), name='teacher_signup'), path('students/', include(([ path('', students.dashboard, name='quiz_list'), path('logout', students.logout_request, name="logout"), path('dashboard', students.dashboard, name='app-student-dashboard'), path('directory_grid', students.directory_grid, name='app-directory-grid'), path('take_course', students.take_course, name='app-take-course'), path('edit_user', students.edit_user, name='edit_user'), path('mentors', students.mentor_list, name='mentors'), ], 'classroom'), namespace='students')), path('teachers/', include(([ path('', teachers.QuizListView.as_view(), name='app-instructor-dashboard'), path('logout', teachers.logout_request, name="logout"), path('edit_user', teachers.edit_user, name='edit_user'), path('mentor_messages', teachers.mentor_messages, name='mentor_messages'), path('statement', teachers.statement, name='app-instructor-statement'), path('course_details', teachers.course_details, name='app-take-course'), … -
django with mysql database partition not work "architect "
i have a big database with django, i use "mysql", the number of rows increasing every month about 100 millions of rows, for that : i have to implement a mysql database partition with django , i tried to install 'architect package' and configure the table class as the following , "my app name is app1 , my project name c4" : models.py file: @architect.install('partition', type='range', subtype='date', constraint='month', column='Timestamp') class acc_start(models.Model): username = models.CharField(max_length=50) ip = models.CharField(max_length=50) Acct_type = models.CharField(max_length=50) Session_Id = models.CharField(max_length=50) Timestamp = models.DateTimeField() Tunnel_Client = models.CharField(max_length=50) NAT_IP_Address = models.CharField(max_length=50) Start_Port = models.CharField(max_length=50) End_Port = models.CharField(max_length=50) post_date = models.DateTimeField() procedure_check_start = models.IntegerField() class Meta: db_table = "acc_start" after that i execute the follwing command on windows : set DJANGO_SETTINGS_MODULE=c4.settings and then when try to execute the partition command : architect partition --module app1.models i see error like the photo error photo but the "architect partition" works normally when i try to make "migrate" and then "architect partition" ,like the following : python manage.py makemigrations Migrations for 'app1': app1\migrations\0026_acc_start.py - Create model acc_start c:\course\c4>python manage.py migrate System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes … -
python get url from request
i get data from an api in django. The data comes from an order form from another website. The data also includes an url, for example like example.com but i can't validate the input because i don't have access to the order form. The url that i get can also have different kinds. More examples: example.de http://example.de www.example.com https://example.de http://www.example.de https://www.example.de Now i would like to open the url to get the correct url. For example if i open example.com in my browser, i got the correct url http://example.com/ and that is what i wish for all urls. How can i do that in python fast? -
multiple text watermark on image PIL django python
currently its drawing one text on thumbnail and i want to draw multiple small text watermark on thumbnail models.py: class Image(models.Model): license_type = ( ('Royalty-Free','Royalty-Free'), ('Rights-Managed','Rights-Managed') ) image_number = models.CharField(default=random_image_number,max_length=12,unique=True) title = models.CharField(default=random_image_number,max_length = 100) image = models.ImageField(upload_to = 'image' , default = 'demo/demo.png') thumbnail = models.ImageField(upload_to='thumbs', blank=True, null=True) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) shoot = models.ForeignKey(ImageShoot, on_delete=models.CASCADE, related_name='Image', null=True,blank=True) image_keyword = models.CharField(max_length=500) description = models.TextField(max_length=3000,null=True,blank=True) credit = models.CharField(max_length=150, null=True,blank=True) location = models.CharField(max_length=100, null=True,blank=True) license_type = models.CharField(max_length=20,choices=license_type, default='') uploaded_at = models.TimeField(auto_now_add=True) def __str__(self): return self.title def save(self, *args, **kwargs): super(Image, self).save(*args, **kwargs) if not self.make_thumbnail(): raise Exception('Could not create thumbnail - is the file type valid?') def make_thumbnail(self): fh = storage.open(self.image.path) base = PILImage.open(fh).convert('RGBA') base.load() width, height = base.size txt = PILImage.new('RGBA', base.size, (255,255,255,0)) fnt = ImageFont.truetype('arial.ttf', 300) d = ImageDraw.Draw(txt) for x_ratio in range(0, 7): x = width * x_ratio/7 + width/20 for y_ratio in range(0, 7): y = height * y_ratio/7 + height/20 d.text((x,y), "liveimages.in", font=fnt, fill=(255,255,255,128)) txt = txt.rotate(45) out = PILImage.alpha_composite(base, txt) out.thumbnail((1000,1000),PILImage.ANTIALIAS) fh.close() thumb_name, thumb_extension = os.path.splitext(self.image.name) thumb_extension = thumb_extension.lower() thumb_filename = thumb_name + '_thumb' + thumb_extension if thumb_extension in ['.jpg', '.jpeg']: FTYPE = 'JPEG' elif thumb_extension == '.gif': FTYPE = 'GIF' elif thumb_extension … -
TypeError: wrapper() got an unexpected keyword argument 'force_insert' Django
I am writing TestCase in Django for test of creating object from view. I got this error when I try to save my object. What is the problem ? How to fix this? class FlowModelTest(TestCase): @classmethod def setUpTestData(cls): cls.flow = models.Flow.objects.create( name='test', description='test', parameters='test', ) def test_flow_max_lengths(self): name_max_length = self.flow._meta.get_field('name').max_length self.assertEqual(name_max_length, 128) parameters_max_length = \ self.flow._meta.get_field('parameters').max_length self.assertEqual(parameters_max_length, 256) def test_flow_str(self): flow_str = str(self.flow) self.assertEqual(flow_str, self.flow.name) Traceback: ERROR: setUpClass (db_visual.tests.tests_model.FlowModelTest) Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/test/testcases.py", line 1137, in setUpClass cls.setUpTestData() File "/app/src/db_visual/tests/tests_model.py", line 11, in setUpTestData cls.flow = models.Flow.objects.create( File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 422, in create obj.save(force_insert=True, using=self.db) TypeError: wrapper() got an unexpected keyword argument 'force_insert' -
How to serve django and gatsby on single vhost?
I'm trying to deploy gatsby based frontend with django based backend under a single domain. It will rely on Apache and mod_wsgi. In a perfect world it should work as following: https://my-domain.com/ - gatsby frontend https://my-domain.com/admin - django https://my-domain.com/api - django I can see two possibilities: Django is aware of frontend. Serve everything via Django, setup / as a STATIC_URL. Django is not aware of frontend. Serve /api and /admin via django. / is handled by a webserver. I feel more comfortable with the second approach, however I do not know how to configure VirtualHost for such a scenario. The firstch approach looks like an ugly hack. How should I proceed with that? -
I dont see models in django-admin which created from drf
I create and save user from django-rest-framework, but it do when i am anonymous user. Now i dont see those model in django-admin. How to add model to django-admin? admin.py from django.contrib import admin from possible_blacklist.models import PossibleBlacklist class PossibleBlacklistAdmin(admin.ModelAdmin): list_display = [field.name for field in PossibleBlacklist._meta.get_fields()] admin.site.register(PossibleBlacklist, PossibleBlacklistAdmin) serializers.py from rest_framework import serializers from possible_blacklist.models import PossibleBlacklist class PossibleBlacklistSerializer(serializers.ModelSerializer): class Meta: model = PossibleBlacklist fields = '__all__' def create(self, validated_data): return PossibleBlacklist.objects.create(**validated_data) def validate_mobile_phone(self, data): if data.startswith('0'): raise serializers.ValidationError("Номер должен начинаться на +380") return data -
javascript var sent to django over html
I have a javascript and calculate with a variable (array). now I want to send this varibale back to django (view.py) with the html button. the button also sends some field entries. the html-code looks something like this: <script> var fibo = [1, 1, 2, 3, 5, 8]; </script> <form class="form-inline" action ="{% url 'new:calculation' %}" method="post"> {% for field in fields %} ... {% endfor %} <button type="submit" class="btn btn-primary">calculation</button> </form> how can I now send the variable fibo? I've already thought about creating invisible fields and loading them with the values of the array, but find that dirty ... -
graphql-django update mutation with optional fields idiom?
When implementing GraphQL update mutations with many (here just a and b) optional InputObjectType fields it generates a lot of boilerplate to check if the InputObjectTypes fields have been passed. Is there some idiom which is considered best practice w.r.t. this topic? # <app>/models.py from django.db import models class Something(models.Model): a = models.CharField(default='') b = models.CharField(default='') # <app>/schema.py import graphene from graphene_django import DjangoObjectType from .models import Something class SomethingType(DjangoObjectType): class Meta: model = Something class SomethingInput(graphene.InputObjectType): # all fields are optional a = graphene.String() b = graphene.String() class SomethingUpdateMutation(graphene.Mutation): class Arguments: id = graphene.ID(required=True) something_data = SomethingInput(required=True) something = graphene.Field(SomethingType) def mutate(self, info, id, something_data): something_db = Something.objects.get(pk=id) # TODO: check if optional fields have been passed here, # only change corresponding db value if value has been passed something_db.a = something_data.a something_db.b = something_data.b something_db.save() return SomethingUpdateMutation(something=something) class Mutation(object): # project schema inherits from this class something_update_mutation = SomethingUpdateMutation.Field() -
Does transaction.atomic works with mongoengine as well
I'm aware that we can manage db transaction to maintain transaction.atomic(), it works really well with SQL, just wanted to understand if I use mongoengine as ODM then will it work or if not what option do I have to maintain atomicity? Any help will be useful -
python code for retrieving data related to Gmail account with profile image
python based API for google auth which help for retrieving user's account information and image also -
Django Crispy Forms template does not exist error
I installed django crispy forms registered under installed apps and loaded it in my template register.html am getting this error when i run it in my browser what can i do to solve this issue i really need to use crispy forms to beautify my forms -
How can return previous page using django class view
with my code, I can create tempfriend in 3 different page. so I'd like to make when I create tempfriend, I hope return previous page. how can I achieve it? (when I use form_valid, there is no request, so request.META doesn't work. and if I use self.request, it create tempfriend and just return create page.) class tempfriend_create(FormView): form_class = forms.CreateTempfriendForm template_name = "tempfriends/create.html" def form_valid(self, form): tempfriend = form.save() form.instance.belongs_to = self.request.user tempfriend.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) -
How to generate CSV file with Django (dynamic content)
so i have this model class base view class ReportView(ListView): model = Pv template_name = 'pv/report.html' context_object_name = 'all_search_results' def get_queryset(self): result = super(ReportView, self).get_queryset() query = self.request.GET.get('search') today = datetime.datetime.now() if query: if query == "Withholding": postresult = Pv.objects.filter(Withholding_tax__gt =0.00,Date_recieved__year=today.year) elif query =="Non-Withholding": postresult = Pv.objects.filter(Withholding_tax__lte =0.00,\ Date_recieved__year=today.year) elif query =="Accountable-Impress": postresult = Pv.objects.filter(Acc_Impress__exact ='Yes',Date_recieved__year=today.year) elif query =="Non-Accountable-Impress": postresult = Pv.objects.filter(Acc_Impress__exact = 'No',Date_recieved__year=today.year) else: postresult = Pv.objects.all() result = postresult else: result = None return result now my problem is to generate a dynamic csv file based on the value of query. please any help would do am kind of new to django . thank u very much