Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get Deadline Date exclude weekends
How to get the exact Deadline date not the number of days in Django Models exclude weekends? My code work good but I want to exclude weekends. Deadline = models.DateTimeField(default=datetime.datetime.today() + timedelta(days=15)) -
I need to append a value in an array to another value in python
This is the current json response [ [ { "TO":"nathanoluwaseyi@gmail.com", "FROM":"johndoe@gmail.com", "SUBJECT":"This is the subject 1", "MESSAGE":[ "First Message" ], "NAME":"John Doe", "DATE":"2019-08-18 19:48:10" }, { "TO":"nathanoluwaseyi@gmail.com", "FROM":"johndoe@gmail.com", "SUBJECT":"This is the subject 2", "MESSAGE":[ "Second message" ], "NAME":"John Doe", "DATE":"2019-08-18 19:48:10" } ] ] But i want a situation whereby more than one of the response have the same FROM then, the MESSAGE should be together in this format or something like this. How do i go about this? Everything i have tried didn't work [ [ { "TO":"nathanoluwaseyi@gmail.com", "FROM":"johndoe@gmail.com", "SUBJECT":"This is the subject 1", "MESSAGE":[ "First Message", "Second Message" ], "NAME":"John Doe", "DATE":"2019-08-18 19:48:10" } ] ] -
How to check duplicates in extended user model
model--- class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) Mobile =models.CharField(max_length=15,default="") def __str__(self): return self.user.username form---- class UserProfileForm(forms.ModelForm): Mobile = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myinput', 'placeholder':'Mobile Number','title':'Please Enter Phone Number Without Country Code, Eg:9999999999 '}),min_length=10, max_length= 15, required =True ,validators = [clean_phone, ]) class Meta: model = UserProfile fields=('Mobile',) def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields['Mobile'].widget.attrs.update({'class' : 'myinput' ,'placeholder':'Mobile Number','title':'Please Enter Phone Number Without Country Code, Eg:9999999999 '}) view--- signup form def signup (request): if request.method =="POST": form = signupForm(request.POST or None) userprofile =UserProfileForm(request.POST or None) if form.is_valid() and userprofile.is_valid(): try: First_Name= form.cleaned_data['Name'] email= form.cleaned_data['email'] password= form.cleaned_data['password'] re_password= form.cleaned_data['re_password'] mobile= userprofile.cleaned_data['Mobile'] print(User.userprofile) if User.objects.filter(username=email).exists() or User.objects.filter(email=email).exists(): print("Email id is already taken") elif User.userprofile.objects.filter(mobile=mobile).exsist(): print("Mobile Number already taken ") i would like to know whether mobile number is already available in the Userprofile -
Add a variable for all logs in python using logging module
I am printing logs using a logging module. and am using the dictConfig like following. logging.config.dictConfig( { "version": 1, "disable_existing_loggers": False, "formatters": { "console": {"format": "%(name)-12s %(levelname)-8s %(message)s"}, "file": {"format": "%(asctime)s %(name)-12s %(levelname)-8s %(message)s"}, }, "handlers": { "console": {"class": "logging.StreamHandler", "formatter": "console"}, "file": { "level": "DEBUG", "class": "logging.FileHandler", "formatter": "file", "filename": "/tmp/debug.log", }, }, "loggers": {"": {"level": "DEBUG", "handlers": ["console", "file"]}}, } ) Now I received an email for each request that comes to the server in the middleware. I want to add that email to all of the logs in the format string. How Can I achieve this? -
How do I send csrftoken from Django Rest Framework backend to React Native front-end?
I am building an application after finishing up my website. Now, the backend for both of these should be common, but Django's csrf token is meant to be a security against this. Since I am not using a web browser, I am unable to get a csrf token cookie. At the same time, django will need it to access its APIs. Is there any way I can get the cookie from Django and get it into React Native? -
Having trouble with Django URLS
So I am getting the error TypeError: view must be a callable or a list/tuple in the case of include(). Here is my code from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] -
Overlapping of multiple plots in Django
I am building a web application using Django that has an option of plotting plots like histograms, scatterplots, bar charts etc Using matplotlib lib, I am plotting the plots and rendering the plots to HTML pages. plt.figure() plt.title("xyz") plt.tight_layout() plt.plot(x,y, 'b') plt.plot(x,z, 'r') buf = BytesIO() fig = plt.gcf() fig.set_size_inches(12,8, forward=True) fig.savefig(buf, format='png') plt.clf() # Get Image image_base64 = base64.b64encode( buf.getvalue()).decode('utf-8').replace('\n', '') img_src = 'data:image/png;base64, {}'.format(image_base64) When a user sends two different requests to plot different plots, the content like legend and data points are mixing with other plots and results in an overlap of plots. This is the first time am posting a query and please let me know if any additional information is required for a better understanding of the problem. Any help would be appreciated. Thanks -
Increase plot size in mobile view of django application
I am trying to develop a test web application using django. My app has a section where I show a plotly graph in my template. Things are fine until then when I saw that the plotly graph is very diminished in the mobile view but looks great in the webview. Need help in increasing the plot size in mobile view. -
Django Check Constraint for MySQL 5.7 alternatives
To my dismay (after being so excited to use it), CheckConstraints are not available on MySQL DBs less than 8.0.16. I'm using MySQL 5.7 and doesn't look like I'll be updating any time soon. I'm using Django v2.2 and wanted to apply the new constraints to my DB: https://docs.djangoproject.com/en/2.2/ref/models/constraints/ (The docs may need to be updated to say that check constraints don't work with MySQL versions less than xyz) I want to know if anyone has a good working alternative for this use case. I've currently whipped up a signal on pre_save to raise an IntegrityError if the constraint matches. @receiver(pre_save) def object_constraint(sender, instance, **kwargs): if issubclass(sender, MyClass): if instance.constraint_is_met: raise IntegrityError("What are you even...?") Thanks -
Can anyone help me to create update view in django?
``` views.py class DreamHeroView(CreateView): template_name = 'dream_hero.html' model = Character form_class = DreamHeroForm def get(self, *args, **kwargs): form = DreamHeroForm() return render(self.request, 'dream_hero.html', {'form': form}) def post(self, *args, **kwargs): form = DreamHeroForm(self.request.POST, self.request.FILES or None) if form.is_valid(): title = form.cleaned_data['title'] description = form.cleaned_data['description'] strenght = form.cleaned_data['strenght'] power = form.cleaned_data['power'] weapon = form.cleaned_data['weapon'] hero_image = form.cleaned_data['hero_image'] slug = form.cleaned_data['slug'] post = Character( title=title, description=description, strenght=strenght, power=power, weapon=weapon, hero_image=hero_image, slug=slug, user=self.request.user, ) post.save() return redirect('character-post') return render(self.request, 'dream_hero.html') ``` views.py class StoryDetailView(FormMixin, DetailView): model = Character template_name = 'story.html' context_object_name = 'comment_set' form_class = CharCommentForm def get_context_data(self, **kwargs): context = super(StoryDetailView, self).get_context_data(**kwargs) context['commenting'] = self.object.charactercomment_set.all() context['pro_pic'] = get_object_or_404(Author, user=self.request.user) context['charform'] = CharCommentForm() return context def get_success_url(self): return reverse('story-post', kwargs={ 'slug': self.object.slug }) def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.instance.user = self.request.user form.instance.post = self.get_object() form.save() return super().form_valid(form) ``` form.py class DreamHeroForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Name of your hero' })) description = forms.CharField(widget=forms.Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Story of your Hero' })) slug = forms.SlugField() hero_image = forms.ImageField() strenght = forms.IntegerField() power = forms.IntegerField() weapon = forms.IntegerField() -
Could not parse the remainder: '% form.as_p %' from '% form.as_p %'
I have a error with Django: I think everything is correct but I don't understand this error Cloud you help me please? Could not parse the remainder: '% form.as_p %' from '% form.as_p %' <form action="{% url 'learning_logs:new_topic' %}" method = 'post'> {% csrf_token %} {{% form.as_p %}} -
i wanna have two ways to add imag to my site one through url and other through my pc storage
so i wanna have two different options to upload an image to the website one through src="{{ product.image_url }} so i can display the image through a url i provide and the other option i wanna keep is to add an image through pc storage like from desktop. I have already setup the displaying of image through url but now i want to to add a way were if i cant find the image url i can just upload an image through my pc. Here is all the code admin.py from django.contrib import admin from .models import Product, Offer class OfferAdmin(admin.ModelAdmin): list_display = ('code', 'discount') class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'stock') admin.site.register(Product, ProductAdmin) admin.site.register(Offer, OfferAdmin) apps.py from django.apps import AppConfig class ProductsConfig(AppConfig): name = 'products' models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Offer(models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=255) discount = models.FloatField() urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] views.py from django.http import HttpResponse from django.shortcuts import render from .models import Product def index(request): products = Product.objects.all() return render(request, 'index.html', {'products': products}) def new(request): return HttpResponse('New … -
How can i store a python list into my mongodb from my views.py
My problem may be really simple cause im new to django.. I have a model and a form that work as expected. I type in my template, a project_name and a subnet address and i store them in the database. What if i want to store in that model a python list too? The list i want to save is being generated in my views.py function after the user submits the project name and the subnet. What changes must i do in order to achieve that? Code below: forms.py class LanModelForm(forms.ModelForm): helper = FormHelper() # helper.form_show_labels = False class Meta: model = UserProject fields = ['project_name', 'subnet', ] models.py class UserProject(models.Model): project_name = models.CharField(max_length=15) subnet = models.CharField(max_length=30) def __str__(self): return self.project_name views.py . . . elif request.POST.get('Arp'): print('ARP-PING code accessed') # _target = request.session['target'] _target = request.session.get('subnet') ans, _ = srp(Ether(dst='ff:ff:ff:ff:ff:ff') / ARP(pdst=_target), timeout=3, verbose=0) clients = [] for sent, received in ans: clients.append({'IP': received[1].psrc, 'MAC': received[1].hwsrc}) print('AVAILABLE CLIENTS IN THE NETWORK:') for client in clients: print('{} {}'.format(client['IP'], client['MAC'])) context = { 'error_message': 'Nothing found,try another subnet!', 'subnet': _target, 'arp_clients': clients, } return render(request, 'projectRelated/passive_scanning.html', context) -
Not using user = models.OneToOneField(User,on_delete=models.CASCADE)
I am creating the registration,login, logout which requires only email and password. When I use user = models.OneToOneField(User,on_delete=models.CASCADE) it gives me an error because it requires username too. How can I take only email and password from User and save it to user? -
Can't find the template - Django
In my Django project I have two apps, called data_app and user_app. The data_app works perfectly, but user_app not. When I write in my browser http://127.0.0.1:8000/login/ appears the following error, django.template.exceptions.TemplateDoesNotExist: /login.html Probably I'm forgetting something, but I don't know what. Then, I show the different parts and my structure, views.py from django.shortcuts import render # Create your views here. from django.shortcuts import redirect from django.contrib.auth.models import User, auth from django.contrib import messages def login(request): if request.method == 'POST': username = request.POST['uname'] password = request.POST['pass'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request,user) return redirect('/data_app/data-bbdd/') else: return redirect('login') else: print('Hello2') return render(request, '/login.html') def logout(request): auth.logout(request) return redirect('login') urls.py (user_app) from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('login/', views.login, name='login'), path('logout/', views.logout, name='logout') ] urls.py ("general" app) from django.contrib import admin from django.urls import path, re_path, include urlpatterns = [ path('admin/', admin.site.urls), re_path('', include('applications.data_app.urls')), re_path('', include('applications.user_app.urls')) ] Estructure I suppose I'm forgetting some path, but I can't see were. Note The print('Hello2') from views.py is working, the the problem is in return render(request, '/login.html'). Thank you very much! -
Validation erorr raise for the form that validates its value from another model
I am trying to raise validation error for the entry field in the forms.py My models.py class StudBackground(models.Model): stud_name=models.CharField(max_length=200) class Student(models.Model): name=models.CharField(max_length=200) My forms.py class StudentForm(forms.ModelForm): name = forms.CharField(max_length=150, label='',widget= forms.TextInput) class Meta: model = Student fields = ['name',] where i tried to apply clean method : def clean_student(self,*args,**kwargs): name=self.cleaned_data.get("name") if not studBackground.stud_name in name: raise forms.ValidationError ( "It is a not valid student") else: return name My form takes name from the form entry field and then requests from DB whether name in DB based on my StudBackground model. I tried to incorporate stud_name from the StudBackground model to the form but it does not work it raises following error when i try to type student name that is not in DB: Profiles matching query does not exist however it supposed to return near the name field "It is a not valid student" How to make it work? What is the wrong with the code. I am learning Django and would appreciate your help and any thought on that. -
No module named 'urllib2' rapportive - Python 3.8.2
I am looking for the files but did not found any urllib2 ModuleNot How can I solve it? I am too beginner in python I am just looking at this extension for my working purposes can anyone please help. here is the post from where I collected this extension https://github.com/andrealmieda/rapportive Thanks in advance -
How to apply __contains to formatted date with django ORM?
I want to implement a database search and I need to filter queryset by date that contains search request. The problem is that users will see formatted date (like dd.mm.yyyy) and will expect search to see it the same way, but default __contains consider date in yyyy-mm-dd format. How can I apply filter to DateField before using __contains? I need a way using django orm because otherwise it will be too long (not using sql). I tried to set DATE_FORMAT = 'd.m.Y' to satisfying format but it has no effect (even setting USE_L10N = False) Also thought about creating custom lookup but not sure how to implement it -
How could the form display data that it takes from database? (similar to google sheets cells concept)
I'm developing notes taking app and want to create the following: I have: class Ticket(models.Model): ticket_num = models.IntegerField(default=0) post = models.CharField(max_length=000) date = models.DateTimeField(auto_now=True) when I do the view like this: def get(self, request): form = TicketsForm(initial={'post':Ticket.post}) my form displays < django.db.models.query_utils.DeferredAttribute object at 0x10e0a92b0 > I think I'm almost there but something goes wrong here %) It should work exactly like google sheets but the only difference might be that the submitting will be made by button. if you could help to make it exactly like google sheets that'd be awesome! -
ajax response is sending data but not getting any response
i am sending a data via ajax on POST method , the problem is that it sends data but it don't recieves it and it also dont renders html page. views.py def checkoutnow(request): my_dict = {} name_dict = {} final_dict = {} record=0 total_price = 0 if request.method == 'POST': print(type(request.POST)) m = request.POST print("length",len(m)) for k,v in m.items(): print(k,"and ", v) my_dict.update({k: v}) key = my_dict.pop("csrfmiddlewaretoken") #print(my_dict) print(key) for p in range(int(len(my_dict)/5)): name = m[f'object[{p}][name]'] qty = m[f'object[{p}][qty]'] name_dict.update({name: qty}) #print("zz",name_dict) for n, q in name_dict.items(): print(n , q) if newarrival.objects.filter(product_name__contains=n): db = newarrival.objects.filter(product_name__contains=n) print("price",db[0].price * int(q)) price = db[0].price * int(q) print("na", price) elif womentrouser.objects.filter(product_name__contains=n): db = womentrouser.objects.filter(product_name__contains=n) print("price", db[0].price) price = db[0].price * int(q) print("wt",price) elif womenshirt.objects.filter(product_name__contains=n): db = womenshirt.objects.filter(product_name__contains=n) print("price", db[0].price) price = db[0].price * int(q) print("ws",price) elif mentrouser.objects.filter(product_name__contains=n): db = mentrouser.objects.filter(product_name__contains=n) print("price", db[0].price) price = db[0].price * int(q) print("mt",price) elif menshirt.objects.filter(product_name__contains=n): db = menshirt.objects.filter(product_name__contains=n) print("price", db[0].price) price = db[0].price * int(q) print("ms",price) elif equipment.objects.filter(product_name__contains=n): db = equipment.objects.filter(product_name__contains=n) print("price", db[0].price) price = db[0].price * int(q) print("eq",price) else: print("didnt match") d = {record: [n, q, price]} record = record + 1 final_dict.update(d) print(final_dict) print(final_dict[1][2]) print(len(final_dict)) for j in range(int(len(final_dict))): print("this is j",j) total_price += final_dict[j][2] print(total_price) return … -
'function' object has no attribute 'objects' Django, help me
I'm designing a Django app and experiencing an error message: AttributeError at / 'function' object has no attribute 'objects' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.10 Exception Type: AttributeError Exception Value: 'function' object has no attribute 'objects' This is my views.py that generates the message: from django.shortcuts import render from post.models import posts def index(request): featured = Post.objects.filter(featured=True) context = { 'object_list': featured } return render(request, 'index.html', context) def blog(request): return render(request, 'blog.html', {}) def Post(request): return render(request, 'post.html', {})` and this is my model.py from django.db import models from django.contrib.auth import get_user_model user = get_user_model() class author(models.Model): user = models.OneToOneField(user, on_delete=models.CASCADE) profile_picture = models.ImageField class category(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class posts(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) comment_count = models.IntegerField(default=0) author = models.ForeignKey(author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(category) featured = models.BooleanField() def __str__(self): return self.title Thanks for any help. -
Is there a way to make foreign key from an attribute to another from other class in django?
class Assignatura(models.Model): """docstring for Assignatura""" nom = models.CharField(max_length = 40) codi = models.IntegerField() any_academic = models.CharField(max_length = 7) class Matricula(models.Model): """docstring for Matricula""" nia_alumne = models.ForeignKey(Alumne, null = False, on_delete=models.CASCADE, verbose_name = 'Nom alumfne') codi_assignatura = models.ForeignKey(Assignatura, null = False, on_delete=models.CASCADE) any_academic = models.CharField(max_length = 7) image = models.ImageField(upload_to="matriculas", null=True) i Want that codi_assignatura gets only codi from Assignatura -
Reverse for 'post' with keyword arguments '{'pk': 8}' not found. 1 pattern(s) tried: ['Loader/post/$'] "DANGO"
urls.py app_name = 'Loader' urlpatterns = [ path('post_detail/', views.Loader_post_view.as_view(), name="post_detail"), path('post/', views.post.as_view(), name="post"), path('my_job/', views.Loader_post_list.as_view(), name="my_job"), path('delete/<int:pk>', views.Loader_post_delete.as_view(), name="Delete"), path('update/<int:pk>', views.Loader_post_update.as_view(template_name="post_detail.html"), name="Update") ] this is my models.py class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) sending_item = models.CharField(max_length=150) #image_of_load = models.ImageField(default='',upload_to='static/img') weight = models.CharField(max_length=150) metric_unit = models.CharField(max_length=30, default='') quantity = models.PositiveIntegerField() pick_up_time = models.DateField() drop_time = models.DateField() paid_by = models.CharField(max_length=150) created_at = models.DateTimeField(auto_now=True) published_date = models.DateField(blank=True, null=True) def __str__(self): return self.user.username def get_absolute_url(self): return reverse("Loader:post", kwargs={'pk': self.pk}) this if my views.py class Loader_post_view(CreateView,LoginRequiredMixin): form_class = forms.Loader_post_form model = Loader_post template_name = "post_detail.html" def form_valid(self, form): print(form.cleaned_data) self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) this is my post form in html <form method="POST"> {% csrf_token %} <div class="container"> <div class="form-row"> <div class="col">{% render_field form.pick_up_station class="form-control" placeholder="Enter pick_up_station"%}</div> <div class="col">{% render_field form.destination_station class="form-control" placeholder="Enter destination_station"%}</div> </div> <div class="form-row"> <div class="col">{% render_field form.sender_name class="form-control" placeholder="Enter sender_name"%}</div> <div class="col">{% render_field form.phone_number class="form-control" placeholder="Enter phone_number"%}</div> </div> <div class="form-row"> <div class="col">{% render_field form.receiver_name class="form-control" placeholder="Enter receiver name"%}</div> <div class="col">{% render_field form.sending_item class="form-control" placeholder="Enter sending_item"%}</div> </div> <div class="form-row"> <div class="col">{% render_field form.weight class="form-control" placeholder="Enter weight"%}</div> <div class="col">{% render_field form.metric_unit … -
Django/Python: Adding incrementing numbers to bulk of usernames
I am creating a game where I have a player list, and when a game is created a list of players (users) is generated. The function below creates a player with random usernames, for example "Player_0tt". I wish to instead of having random ascii_lowercase + digits, to increment each user by 1. So the first user is called Player_1, Player_2..etc. I will be adding the game ID to the username to make each game users unique but for now I am trying to get the 1, 2, 3...behind my usernames. Should I make a new function that increments, or is there a smarter way to do this? Create random username def generate_username(length=3, chars=ascii_lowercase + digits, split=7, delimiter='_'): username = 'Player' + ''.join([choice(chars) for i in range(length)]) if split: username = delimiter.join([username[start:start + split] for start in range(0, len(username), split)]) try: User.objects.get(username=username) return generate_random_username(length=length, chars=chars, split=split, delimiter=delimiter) except User.DoesNotExist: return username -
Django: Creating model managers does not work
Please help me ... I understand that the problem is very simple ... but I'm stuck! I Creating model managers class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): ................... objects = models.Manager() published = PublishedManager() and this is what I get in the terminal >>> Post.objects.filter(publish__year=2020, author__username='sasa') <QuerySet [<Post: try>, <Post: 3 article>]> >>> Post.published.filter(publish__year=2020, author__username='sasa') <QuerySet []> >>> Post.object.filter... works correctly, but Post.published.filter returns an empty object This is not right? Where am I mistaken?