Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to convert ImageField to video html5 tag to take pricture - django
I've a project one of the models has image field to upload picture , i made it modelformset_factory to upload multiple images , but from webcam ! is there any django tips or modules to do that ? i tried this but i cant take more than one picture , and cant assign taken photo into the ImageField? my image upload model class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) def __str__(self): return str(self.booking.id) my forms.py class UploadDocumentsForm(forms.ModelForm): class Meta: model = Document fields = ['docs'] UploadDocumentFormSet = modelformset_factory(Document,form=UploadDocumentsForm,extra=1,can_delete=True) my views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': images = UploadDocumentFormSet(request.POST,request.FILES) if images.is_valid(): for img in images: if img.is_valid() and img.cleaned_data !={}: img_post = img.save(commit=False) img_post.booking = obj img_post.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('take a picture or choose an image')) images = UploadDocumentFormSet(queryset=Document.objects.none()) return render(request,'booking/add_img.html',{'obj':obj,'images':images}) const player = document.getElementById('player'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const captureButton = document.getElementById('capture'); const constraints = { video: true, }; captureButton.addEventListener('click', (e) => { // Draw the video frame to the canvas. context.drawImage(player, 0, 0, canvas.width, canvas.height); e.preventDefault(); }); // Attach the video stream to the video element and autoplay. navigator.mediaDevices.getUserMedia(constraints) .then((stream) => { player.srcObject = stream; }); $('#addButton').click(function() { var … -
Using apscheduler to run Django serializer code every 15 minutes and updates it's data
using serializers I wrote some code that will ssh to different machines and return some information about these machines. Every time I refresh my page, the code will ssh to the system and return real time data. After noticing how long it takes to ssh to the machines to return data and some other issues, I figured this approach is not the best. I would like to save whatever result I git from the ssh in a database/cache and retrieve this data when I refresh the page from the database/cache. I thought of using an apscheduler and have the serializer update it's data every 15 minutes instead of every time I refresh the page (ssh once every 15 minutes). I am not sure if this will work or if there are better ways to achieve this. I would be thankful if you guys give some pointers. Currently my serializer results are not saved in the database. So to achieve this do I need to save the results of the serializer in the database? and will apscheduler do the trick? -
How to sum up numbers for a foreign key model in djnago
I want to sum up the total number of votes made for a login in user that has an award going on. An award is having multiple categories and multiple nominations, what am trying to do is show the sum of votes all nominations that is related to an award model.py class Award(models.Model): Admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100) image = models.ImageField(upload_to='award_images') slug = models.SlugField(max_length=150) about_the_award = models.TextField(blank=True, null=True) price = models.CharField(max_length=20, choices=PRICE, default='0.5') amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2) date = models.DateTimeField(auto_now_add=True) class Category(models.Model): Award = models.ForeignKey(Award, on_delete=models.CASCADE) category = models.CharField(max_length=100,) slug = models.SlugField(max_length=150) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.category class Nomination(models.Model): Fullname = models.CharField(max_length=120) Nominee_ID = models.CharField(max_length=100) Category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to='nominations_images') slug = models.SlugField(max_length=150) votes = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) View.py @method_decorator([login_required], name='dispatch') class DashboardView(TemplateView): template_name = 'admin/Dashboard.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user_awards'] = Award.objects.filter(Admin=self.request.user).order_by('-date') context['number_of_votes'] = Award.objects.filter(Admin=self.request.user, self.catgory.nomination).annotate(Sum('amount')) return context -
trying to save dict in my model but getting error due to foreign key
i am unable to get how to resolve this problem.i am trying to save a dict but getting error due to presence of foreign key in my leave model how can i counter this problem. views.py class leaveview(APIView): def post(self,request): token = request.data['jwt'] if not token: raise AuthenticationFailed('Unauthenticated') try: payload = jwt.decode(token,'secret',algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated') user=User.objects.filter(id=payload['id']).first() serializer1=UserSerializers(user).data serializer2 = leaveSerializers(data=request.data) serializer2.is_valid(raise_exception=True) serializer={**serializer1,**request.data} del serializer["jwt"] final_data= leave(**serializer) final_data.save() return Response(data=serializer) models.py class hostel_manager(models.Model): hostel = models.CharField(max_length=100,primary_key=True) class leave(models.Model): name=models.CharField(max_length=100,null = True) father_name=models.CharField(max_length=100,null=True) branch=models.CharField(max_length=40,null=True) coer_id=models.CharField(max_length=12,unique=True,null=True) hostel_name = models.ForeignKey(hostel_manager,on_delete=models.CASCADE) room_no = models.CharField(max_length=10) where_to = models.CharField(max_length=100) reason = models.CharField(max_length=300) start_date = models.CharField(max_length = 100,null=True) end_date = models.CharField(max_length=100,null=True) phone_regex=RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+9999999999'. Up to 12 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17) -
Getting list of context variables out of string
I have the following string in my Django app: "Hello, {{ name }}. I will arrive at {{ time }}". My goal is to come with a list of variables that is used in that string: def my_func(): # What should be done here ? my_str = "Hello, {{ name }}. I will arrive at {{ time }}" print(my_func(my_str)) # Desired output ["name", "time"] The desired output here should be ["name", "time"]. Currently, I am going to implement that invoking a regexp, but I feel like there must be some in-built function to achieve that. Any hints ? -
python gRPC error: "error": "13 INTERNAL: Failed to serialize response!" when trying to return a repeated message instead of stream in a List Request
I have django REST API that I am trying to convert into gRPC. I followed the Django grpc framework guide and created the following files: models.py class Organization(models.Model): Org_name = models.CharField(max_length=100, unique=True, primary_key=True, db_index=True) Address = models.CharField(max_length=100) Description = models.CharField(max_length=500) Number_of_emp = models.IntegerField() org.proto package org; import "google/protobuf/empty.proto"; service OrganizationController { rpc List(OrganizationListRequest) returns (Organizations) {} rpc Create(Organization) returns (Organization) {} rpc Retrieve(OrganizationRetrieveRequest) returns (Organization) {} rpc Update(Organization) returns (Organization) {} rpc Destroy(Organization) returns (google.protobuf.Empty) {} } message Organization { string Org_name = 1; string Address = 2; string Description = 3; int32 Number_of_emp = 4; } message OrganizationListRequest { } message OrganizationRetrieveRequest { string Org_name = 1; } message Organizations { repeated Organization organization = 1; } Note that Organizations is a message declared in org.proto to return a List or an array of objects services.py class OrganizationService(generics.ModelService): queryset = Organization.objects.all() serializer_class = OrganizationSerializerProto serializers.py class OrganizationSerializerProto(proto_serializers.ModelProtoSerializer): class Meta: model = Organization proto_class = org_pb2.Organization fields = '__all__' Problem I want to make a request using the rpc List(OrganizationListRequest) returns (Organizations) {} to fetch a list of all the organization in the database. However, whenever I make a call to the rpc, I get the following error: request error: … -
Django decorator to redirect to same page?
When a user tries to access a non permitted page, whats the right thing to do ? First option: Redirect to the same page they came from Second Option: Redirect to error page saying permission denied or not found Third Option: Redirect to login page I have created a decorator: from django.contrib.auth.decorators import user_passes_test from django.contrib.auth import REDIRECT_FIELD_NAME def is_student(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): actual_decorator = user_passes_test( lambda u: (u.is_authenticated and u.role == 'role1'), login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator So the above works and redirects to login if we give login_url ! How to redirect to same page from users came or which option is best ? -
Page not found - The current path matched the last one
Pulling my hair out over this. I have created a new update view but I keep getting the error Page not found 404 - The current path, post/118/build-log/54/update/, matched the last one. template: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <a>Update</a> {% endblock content %} view: class BuildLogUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = BuildLog form_class = BuildLogForm template_name = 'buildlog_update.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): BuildLog = self.get_object() if self.request.user.id == BuildLog.author_id: return True return False url: path('post/<int:pk>/build-log/<int:pkz>/update/', BuildLogUpdateView.as_view(), name='build-log-update') most of what i found online was talking about the trailing / on the url but it did not make a difference for me urlpatterns: urlpatterns = [ path('', views.home, name='blog-home'), path('user/<str:pk_user>/', views.UsersCarsPosts, name='user-posts'), path('post/<int:pk>/', views.DetailPostView, name='post-detail'), path('post/<int:post_pk>/comment/<int:pk>/reply/', CommentReplyView.as_view(), name='comment-reply'), path('post/new/', views.createPostView, name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), path('allcars/', views.allCarsView, name='all-cars-url'), path('ajax/allcars/', views.loadModels, name='ajax-allcars'), path('ajax/load-models/', views.loadModels, name='ajax'), path('my-profile/', views.myProfile, name='my-profile'), path('post/<int:pk>/build-log-form/', views.buildLogCreate, name='build-log-form'), path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'), path('post/<int:pk>/build-log/<int:pkz>/delete/', views.BuildLogDelete, name='build-log-delete'), path('post/<int:pk>/build-log/<int:pkz>/update/', BuildLogUpdateView.as_view(), name='build-log-update') ] -
why doesn't echo copy over github secret to .env file
I have a Django app that collects the secret key from a '.env' file in my local directory, I have added this .env to .gitignore so it doesn't get uploaded to github, the only problem is I have now deployed the app to AWS EC2 and I'm using github as a codepipeline, so now the app can't obtain the secret key as it doesn't have the .env file to read from. I've added my secret key to 'github secrets' which is in the repository settings , from what I've read online using echo to get the key and write to a new .env file on startup would work, only problem is the key doesn't echo over to the .env file , yet the file is created with the following command. What's going wrong, please advise on how to fix?: setup_env.sh #!/bin/bash cd /home/ubuntu/djangoapp1/djangoapp1/settings touch .env echo SECRET_KEY=${{ secrets.SECRET_KEY }} > .env appspec.yml version: 0.0 os: linux files: - source: / destination: /home/ubuntu/ hooks: BeforeInstall: - location: scripts/setup_env.sh timeout: 6000 runas: ubuntu AfterInstall: - location: scripts/install_python_dependencies.sh timeout: 6000 runas: ubuntu -
How to download Excel Sheet from Server using openpyxl on Django?
my Frontend calls the Django-Server via AJAX get HTTP Request to export data from the database to an excel-file. Therfore Im using openpyxl. I want to download the HTTP-Response on client side but only get excel files i cannot open or with undefined data. here is my javascript request: $.ajax({ url: '/documentation/export/get' + '/' + var_1 + '/' + var_2, type: 'get', responseType: 'blob', success: function(response) { console.log("EXCEL Success") // var contentType = 'application/vnd.ms-excel'; var contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; var filename = "TEST.xlsx" var blob = new Blob([response], { type: contentType }); var downloadUrl = URL.createObjectURL(blob); var a = document.createElement("a"); a.href = downloadUrl; a.download = filename; document.body.appendChild(a); a.click(); } }); Here is my server-side python code, views.py: from openpyxl import Workbook def documentation_export (request, var_1, var_2): excel_data = [ ['header1', 'header2', 'header3', 'header4', 'header5'], [1,4,5,6,7], [5,6,2,4,8] ] if excel_data: wb = Workbook(write_only=True) ws = wb.create_sheet() for line in excel_data: ws.append(line) response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') # response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=mydata.xlsx' wb.save(response) return response The data for the excelfile / workbook is right now still an exampel from the internet. If I use the code as posted, no download starts at all. If I use the out commented "vnd.ms-excel" instead, I … -
Chaquopy: Python: Is there any way to run Django Apps on Android
I've made a Django Web App which I want to deploy on Android.Recently, I came across a gradle plugin Chaquopy. But as soon as I deploy django app using Chaquopy, It doesn't give desired result and rather gives runtime exceptions.Kindly describe any method using (or even without using) Chaquopy to deploy Django App on Android as .apk -
command and control django server
I am developing a command and control server to control my client-server connected to it via rest API. I am done with Crud APIs for tasks that will be performed but I am having trouble with task management between my client-servers I want to fetch the tasks and then make a single configuration file for all clients but I am not sure what is the best way to do it. I have some ideas please help me figure out the best one :- generate new configuration settings everytime client server perform get call for the configuration settings. this will be slow if i have more tasks. generate new configuration everytime a task is modified, added , deleted along with time stamp. so that clients can check if the config file they are using is old or new compared to the one they received when making get call for configuration. -
Redis not connected with Django in Apache server
Possible SECURITY ATTACK detected. It looks like somebody is sending POST or Host: commands to Redis. This is likely due to an attacker attempting to use Cross Protocol Scripting to compromise your Redis instance. Connection aborted. Please any one can help me on this above error in the apache server -
Django Internationalization : pre choose the language_code but not the one from the settings
Im using django internationalization and im facing a problem: I've been successfully translating my project but i may need more : A user can send a message(the message is known and stored into TextField model ) to an other one, for now if UserA send a message to UserB UserB will receive the message in UserA LANGUAGE_CODE : Can i change it to make UserB to receive message into UserB LANGUAGE_CODE ? Example : UserA is french he selects "envoyer Joyeux anniversaire" to UserB And UserB is english and will receive : "UserA sent you a message :"Joyeux anniversaire" nb: i would rather not show up my code because it's way too big , if you want me to explain my problem with my code ill create a simplest one summarizing the functionalism -
Django custom models.Manager queryset field undefined
I'm implementing a soft delete for class Animal. Following the example in the docs I created a custom manager for it, but the query field, 'Inactive_Date' is undefined. I tried putting the AnimalManager class def inside the Animal class def; no help. Code from models.py: class AnimalManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(Inactive_Date == None) class Animal(models.Model): Name = models.CharField(max_length=64, unique=True) Inactive_Date = models.DateField(null=True, blank=True) Animal_Type = models.ForeignKey(Animal_Type, null=True, on_delete=models.SET_NULL, default=None) Comments = models.CharField(max_length=255, blank=True) def __str__(self) -> str: return (self.Name) def delete(self): self.Inactive_Date = datetime.datetime.today() self.save() objects = AnimalManager() # omits inactive animals -
saving formset by passing it the id of another formset in which it is nested
Hi I have a formset named groups and inside there is another formset named exercises. My problem lies in saving the various formset exercises created in the group formset to which they belong. I am attaching a photo to make you better understand the situation, in the photo the blue boxes (formset exercises) must be saved in the first green box (formset groups) VIEWS def creazioneView(request): gruppiFormSet = formset_factory(GruppiForm, extra=1) eserciziFormSet = formset_factory(EserciziForm, extra=1) if request.method == "POST": schede_form = SchedeForm(request.POST) gruppi_formset = gruppiFormSet(request.POST, prefix='gruppi') esercizi_formset = eserciziFormSet(request.POST, prefix='esercizi') if schede_form.is_valid() and gruppi_formset.is_valid() and esercizi_formset.is_valid(): schedaName = schede_form.cleaned_data['nome_scheda'] scheda = schede_form.save(commit = False) scheda.utente = request.user scheda.save() for gruppo in gruppi_formset: gruppi_instance = gruppo.save(commit = False) gruppi_instance.gruppi_scheda = Schede.objects.get(nome_scheda = schedaName) gruppoName = gruppi_instance.dati_gruppo gruppi_instance.save() for esercizi in esercizi_formset: esercizi_instance = esercizi.save(commit = False) esercizi_instance.gruppo_single = DatiGruppi.objects.get(dati_gruppo = gruppoName) esercizi_instance.save() return redirect('/lista-gruppi/') else: schede_form = SchedeForm() gruppi_formset = gruppiFormSet(prefix='gruppi') esercizi_formset = eserciziFormSet(prefix='esercizi') context = {'schede_form': schede_form, 'gruppi_formset': gruppi_formset, 'esercizi_formset': esercizi_formset} return render(request, "crea.html", context) MODELS class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey(Gruppi, on_delete = models.CASCADE, related_name = 'gruppo') class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey(User, on_delete = … -
Django/python images not displayed
I have tried all combinations (ex: {{ cars.image_main.url }} , {{ car.image_main.url }}). If anyone can give me a hand i will appreciate. I'm beginner in this, i don't have enough time to learn and practice and i follow some times youtube and udemy classes. Im on this for 1 day and my brain is not working at all as far as i can see. Thank you in advance for an advice or solution. models.py: class Car(models.Model): dealer = models.ForeignKey(Dealer, on_delete=models.DO_NOTHING) brand = models.CharField(max_length=100) CATEGORY = ( ('New', 'New'), ('Used', 'Used') ) category = models.CharField(max_length=50, choices=CATEGORY) image_main = models.ImageField(upload_to='images') image1 = models.ImageField(upload_to='images', blank=True) image2 = models.ImageField(upload_to='images', blank=True) image3 = models.ImageField(upload_to='images', blank=True) image4 = models.ImageField(upload_to='images', blank=True) image5 = models.ImageField(upload_to='images', blank=True) image6 = models.ImageField(upload_to='images', blank=True) image7 = models.ImageField(upload_to='images', blank=True) image8 = models.ImageField(upload_to='images', blank=True) image9 = models.ImageField(upload_to='images', blank=True) image10 = models.ImageField(upload_to='images', blank=True) image11 = models.ImageField(upload_to='images', blank=True) image12 = models.ImageField(upload_to='images', blank=True) image13 = models.ImageField(upload_to='images', blank=True) image14 = models.ImageField(upload_to='images', blank=True) image15 = models.ImageField(upload_to='images', blank=True) body_style = models.CharField(max_length=100, blank=True) engine = models.CharField(max_length=100, blank=True) stock_number = models.IntegerField(blank=True, null=True) mpg = models.CharField(max_length=100, blank=True) exterior_color = models.CharField(max_length=100, blank=True) interior_color = models.CharField(max_length=100, blank=True) drivetrain = models.CharField(max_length=100, blank=True) mileage = models.IntegerField(blank=True, null=True) sold = models.BooleanField(default=False, blank=False) transmission = models.CharField(max_length=50, blank=True) YEAR_CHOICES … -
Geeting error during adding a comment as notnull
I don't understand why I am getting this one I tried making null=True, blank=True but still, it does not solve my error, at last, I thought of sending it here ...!! please tell me where I am going wrong Models.py class Certification(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) course_name = models.CharField(max_length=255) course_image = models.ImageField() course_taken = models.CharField(max_length=255) mentor_name = models.CharField(max_length=20, blank=True, null=True) slug = models.SlugField(unique=True, null=True) #body = RichTextField() body = RichTextUploadingField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.course_name class Comment(models.Model): certificate = models.ForeignKey(Certification, on_delete=models.CASCADE) name = models.CharField(max_length=200) body = models.TextField(null=True, blank=True) forms.py class CommentForm(ModelForm): class Meta: model = Comment fields = '__all__' exclude = ['certificate'] def __init__(self, *args, **kwargs): super(CommentForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs.update( {'class': 'form-control form-control-sm',}) self.fields['body'].widget.attrs.update( {'class': 'form-control form-control-sm',}) Views.py def certificatePage(request,pk): certi = Certification.objects.get(id=pk) count = certi.comment_set.count() comments = certi.comment_set.all() form = CommentForm() if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.certi = certi comment.save() context = { "certi": certi, 'count':count, 'comments':comments, 'form':form } return render (request, 'base/certificate.html',context) Click On The Image To See The Error -
defined property on user model not working
I am trying to get the received message count, but i am getting nothing in the template , also i have defined my modal after User , any better way of doing it this property is on User model @property def get_message_count(self): try: messages_count = Messages.objects.filter(message_thread__receiver = self,opened=False).count() except ObjectDoesNotExist: messages_count = 0 return messages_count model class MessageThreads(models.Model): sender = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='sender', null=True) receiver = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='receiver', null=True) created_date = models.DateField(auto_now_add=True) created_time = models.TimeField(auto_now_add=True) class Messages(models.Model): message_thread = models.ForeignKey(MessageThreads,on_delete=models.CASCADE,null=True) message = models.TextField(max_length=600,blank=True) sent_date = models.DateField(auto_now_add=True) sent_time = models.TimeField(auto_now_add=True) opened = models.BooleanField(default=False) def __str__(self): return f"{self.message[:10]}" -
How to populate a model field with a Django signal after updating another model field?
I have a list of tasks that are created by the admin and as the task start dates are set by individual agents, I would like to use a signal to assign the tasks to that agent. Models.py class Task(models.Model): name = models.CharField(max_length=20, blank=True, null=True) agent = models.ForeignKey("Agent", on_delete=models.SET_NULL, null=True) start_date = models.DateField(null=True, blank=True) notes = models.TextField(default=0, null=True, blank=True) -
ImportError: cannot import name 'DjangoDash' from 'django_plotly_dash'
I'm attempting to follow the django-plotly-dash tutorial https://django-plotly-dash.readthedocs.io/en/latest/simple_use.html but when using the code directly from this page: import dash import dash_core_components as dcc import dash_html_components as html from django_plotly_dash import DjangoDash app = DjangoDash('SimpleExample') # replaces dash.Dash app.layout = html.Div([ dcc.RadioItems( id='dropdown-color', options=[{'label': c, 'value': c.lower()} for c in ['Red', 'Green', 'Blue']], value='red' ), html.Div(id='output-color'), dcc.RadioItems( id='dropdown-size', options=[{'label': i, 'value': j} for i, j in [('L','large'), ('M','medium'), ('S','small')]], value='medium' ), html.Div(id='output-size') ]) @app.callback( dash.dependencies.Output('output-color', 'children'), [dash.dependencies.Input('dropdown-color', 'value')]) def callback_color(dropdown_value): return "The selected color is %s." % dropdown_value @app.callback( dash.dependencies.Output('output-size', 'children'), [dash.dependencies.Input('dropdown-color', 'value'), dash.dependencies.Input('dropdown-size', 'value')]) def callback_size(dropdown_color, dropdown_size): return "The chosen T-shirt is a %s %s one." %(dropdown_size, dropdown_color) and trying to run the server, I get the error ImportError: cannot import name 'DjangoDash' from 'django_plotly_dash' Is this deprecated and they haven't updated the tutorial or some other reason? -
NOT NULL constraint failed error when attempting to save using createview
This is my first post to SO, so please let me know if I've missed any important details. I am working on updates to a home-grown DJango based ticketing system. I have two "parent" models (ParentProjects and Projects) that capture details about work we want to track. Both models have a number of columns that store information in the associated table as well as some FK relations. I have set up a generic class-based detail view for objects in both the Project table. The ParentProject table uses a function based view to accomplish the same task of loading the parent project details. The problem I am having is that I cannot add a new entry to the IDTasks model that automatically inserts the Parent Project id. I am able to add a new IDTask from within the admin site (or from the "client" site if I enable the "parent" field within the modelform) and then manually selecting the parent I wish to associate the IDTask to. I can also edit an existing IDTask from within the Parent Project detail template and everything saves successfully. When I attempt to add an IDTask using the createview, Django reports a Not NULL contraint … -
how to disable password in Dj Rest Auth?
i have an application and the new user can only register with OTP message from phone so i want to disable password in API and user can register with OTP only this is my serializers.py class CustomRegisterSerializer(RegisterSerializer): email=serializers.EmailField(required=True) image=serializers.ImageField(required=True) phone=serializers.CharField(required=True) address=serializers.CharField(required=True) gender=serializers.ChoiceField(choices=GENDER,required=True) birthday=serializers.DateField(required=True) password1=serializers.CharField(required=False) password2=serializers.CharField(required=False) def get_cleaned_data(self): super(CustomRegisterSerializer,self).get_cleaned_data() return { 'email': self.validated_data.get('email',""), # 'password1': self.validated_data.get('password1',""), # 'password2': self.validated_data.get('password2',""), 'username': self.validated_data.get('username',""), 'phone': self.validated_data.get('phone',""), 'address': self.validated_data.get('address',""), 'gender': self.validated_data.get('gender',""), 'birthday': self.validated_data.get('birthday',""), 'image': self.validated_data.get('image',"") } def validate_phone(self,value): if Account.objects.filter(phone__iexact=value).exists(): raise ValidationError(f"{value} is already registered") def validate_image(self,value): size=value.size / (1024 * 1024) type=os.path.splitext(value.name)[1] if size > 2 or type != ".jpg": raise ValidationError("image size is more than (2Mb)") def save(self, request): user = super().save(request) user.set_unusable_password() user.username=self.data.get("username") user.first_name=self.data.get("username") user.save() myacount=user.account myacount.image=request.FILES["image"] myacount.type="Patient" myaccount.phone=self.data.get("phone") myaccount.birthday=self.data.get("birthday") myaccount.gender=self.data.get("gender") myaccount.address.add(name=self.data.get("address")) myacount.save() return user i will be very happy for your answer -
Could not find a version that satisfies the requirement pywin32==301 , heroku error
I have tried to remove that file pywin32 from requirements but still it shows this error. I have searched for a method to remove this module but till now I have not found anything useful. This is my requirements.txt file asgiref==3.3.4 astroid==2.7.3 backcall==0.2.0 bcolors==1.0.2 beautifulsoup4==4.9.3 bs4==0.0.1 certifi==2021.5.30 cffi==1.14.6 chardet==4.0.0 cheroot==8.5.2 cloudpickle==1.6.0 colorama==0.4.4 cryptography==3.4.7 decorator==5.0.9 defusedxml==0.7.1 distlib==0.3.2 dj-database-url==0.5.0 Django==3.2.4 django-crispy-forms==1.12.0 django-extensions==3.1.3 django-filter==2.4.0 django-heroku==0.3.1 djangorestframework==3.12.4 filelock==3.0.12 gunicorn==20.1.0 idna==2.10 ipykernel==5.5.5 ipython==7.24.1 ipython-genutils==0.2.0 isort==5.9.3 jaraco.functools==3.3.0 jedi==0.18.0 jupyter-client==6.1.12 jupyter-core==4.7.1 lazy-object-proxy==1.6.0 Markdown==3.3.4 matplotlib-inline==0.1.2 mccabe==0.6.1 more-itertools==8.8.0 oauthlib==3.1.1 parso==0.8.2 pickleshare==0.7.5 Pillow==8.2.0 platformdirs==2.3.0 prompt-toolkit==3.0.19 psycopg2==2.9.1 pycparser==2.20 Pygments==2.9.0 PyJWT==2.1.0 pylint==2.10.2 pymongo==3.11.4 pypiwin32==223;platform_system == "Windows" python-dateutil==2.8.1 python3-openid==3.2.0 pytz==2021.1 pywin32==301;platform_system == "Windows" pyzmq==22.1.0 requests==2.25.1 requests-oauthlib==1.3.0 simplejson==3.17.2 six==1.16.0 social-auth-app-django==5.0.0 social-auth-core==4.1.0 soupsieve==2.2.1 spyder-kernels==2.0.0 sqlparse==0.4.1 termcolor==1.1.0 toml==0.10.2 tornado==6.1 traitlets==5.0.5 urllib3==1.26.5 virtualenv==20.4.7 wcwidth==0.2.5 web.py==0.62 whitenoise==5.3.0 wrapt==1.12. I am getting this error when I use git push heroku master ERROR: Could not find a version that satisfies the requirement pywin32==301 (from -r /tmp/build_53cc9ad9/requirements.txt (line 57)) (from versions: none) remote: ERROR: No matching distribution found for pywin32==301 (from -r /tmp/build_53cc9ad9/requirements.txt (line 57)) This is the full error message Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: eea743c20e6fc3b759e5d6061939723626cbb910 remote: ! remote: ! We have detected that you have … -
Can we use Django-cacheops in Django 3+ versions?
I am updating the django project form 1.3 to Django 3.2 I am trying to use Django-cacheops as I already built in my old version project, but its give me the error of File "C:\Users\mahad\projects\Allay\env\lib\site-packages\cacheops\simple.py", line 9, in <module> from django.utils.hashcompat import md5_constructor ModuleNotFoundError: No module named 'django.utils.hashcompat' Is this library is deprecated or I can use it? If yes then give me the way to do it or kindly refer some extra plugin for saving the cache with redis