Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'NoneType' object has no attribute 'as_sql'
that's ok to makemigrations, but it's error when I migrate. Please give me some advise, I didn't find the same case "as_sql" in Google. Thank you. This is my models class ClinicInfo(models.Model): name_cn = models.CharField(max_length=100, verbose_name=_('Chinese Name')) name_en = models.CharField(max_length=100, verbose_name=_('English Name')) short_name = models.CharField(max_length=10, unique=True, verbose_name=_('Short Name')) address_cn = models.CharField(max_length=200, verbose_name=_('Chinese Address')) address_en = models.CharField(max_length=200, verbose_name=_('English Address')) telnum_1 = models.CharField(max_length=20, verbose_name=_('1st Tel No.')) telnum_2 = models.CharField(max_length=20, blank=True, verbose_name=_('2nd Tel No.')) email = models.EmailField(max_length=254, blank=True, verbose_name=_('Email')) fax = models.CharField(max_length=20, blank=True, verbose_name=_('Fax')) class meta: verbose_name = _('Clinic Information') verbose_name_plural = _('Clinic Information') def __str__(self): return self.name_cn class DoctorArg(models.Model): weekday_list = ( (0, _('Monday')), (1, _('Tuesday')), (2, _('Wednesday')), (3, _('Thursday')), (4, _('Friday')), (5, _('Saturday')), (6, _('Sunday')) ) period_list = ( ('full', _('Full Day')), ('am', _('AM')), ('pm', _('PM')) ) clinic = models.ForeignKey(ClinicInfo, on_delete=models.CASCADE, verbose_name=_('Clinic')) weekday = models.IntegerField( choices=weekday_list, verbose_name=_('Weekday')) period = models.CharField(max_length=4, choices=period_list, default='full', verbose_name=_('Period')) ''' doctor = models.ForeignKey( MyUser, limit_choices_to={'role': 'Doctor'}, on_delete=models.CASCADE, verbose_name=_('Doctor')) ''' class Meta: verbose_name = _('Doctor Arrangement') verbose_name_plural = _('Doctor Arrangements') # unique_together = [['weekday', 'period', 'doctor']] def __str__(self): return 'Doctor arrangements' I didn't find the same case "as_sql" in Google. I tried to trace this error according to this way link, but didn't get debug print. -
What 'namespace' is used for in Django urls?
I have namespace parameter in the urls.py of project, like this: path('blog/', include('blog.urls', namespace='blog')), And then I have app_name = blog in the urls.py of the blog application. I do that because that's what I've learned to do without actually understanding what namespace is doing when app_name is defined? -
What form action should i use to solve error 405 on post?
##html <form id="schedule-form" action="#" method="POST"> {% csrf_token %} .... <input type="submit" id="submit-horario" value="Confirmar" class="btn button-raised btn-green text-white text-uppercase fw-600 me-md-1 mt-3" onclick="gtag_confirmar_horario('S_{{ prestadorservicos.prestadorservicoid }}', '{{ servicoregioes.as_string|escapejs }}', '{{ menor_desconto.get_tipo_de_desconto_display|escapejs }}', '{{ menor_desconto.preco_desconto }}', '{{ prestadorunidade.as_string|escapejs }}', '{{ prestador.parceiro }}', '{{ prestadorservicos.preco }}')"/> </div> </form> ##urls from django.conf.urls import url from django.urls import path from . views import BuscaHorarios, AgendaHorario app_name = "agendamento" urlpatterns = [ url(r'^(?P<prestadorservicosid>[0-9]+)(?:/(?P<unidadeid>[0-9]+))/$', BuscaHorarios.as_view(), name='horarios', ), url('/', AgendaHorario.as_view(), name="agenda_horario"), ] When i submit this form i get 405 http error on console. There is no problem loading (get) this page [25/Mar/2022 11:55:38] "GET /agendamento/11749/1341/ HTTP/1.1" 200 19435 only to submit (post) [25/Mar/2022 11:56:51] "POST /agendamento/11749/1341/ HTTP/1.1" 405 0 -
Using HTML if statements to return results
I am trying to print a list of courses that a user has uploaded onto their account but am having trouble figuring out how to do that. I have tried to print {{ course.student_course }} and {{user.username}} and they both appear to print the same thing. But when I do the comparison in the if statement, nothing returns. Here is the html snippet <div class="container h-100"> <div class="row justify-content-center"> {% if courses_list %} {% for course in courses_list %} {% if course.student_course == user.username %} <button type="button" class="btn btn-outline-primary">{{ subject }} </button> <p>{{ subject }}</p> {% endif %} {% endfor %} {% else %} <p>No courses have been uploaded.</p> {% endif %} </div> </div> And here is the fields of my model that I am trying to access. class Course(models.Model): subject = models.CharField(max_length=4) course_number = models.CharField(max_length=4, default='') course_name = models.CharField(max_length=100, default='') course_section = models.CharField(max_length=3, default='') student_course = models.OneToOneField(User, on_delete=models.CASCADE, default='') def __str__(self): return self.subject + " " + self.course_number Like I said, I tried to print each field being compared and they both turned the same thing but when I try to do the comparison it returns nothing. -
Please critique my Django app (for entry level resume)
Link: https://coleabell05.pythonanywhere.com/home/ Entry level Python/Django oriented programmer here and I just finished a sort of first draft of a simple inventory app linked above I'm planning to use on my resume, launched on pythonanywhere. If anyone has some time, would you mind giving it a look? Hoping for advice on what additional functionality I could work on adding and how I could make it more appealing to recruiters? Also if its structure is confusing at all and what I could change to clarify it's function. As it stands now, it's intended to be a functioning register and inventory manager for a pizzeria. The user makes an account and then has the power to add or delete entrees and ingredients to the kitchen as well as close the register for the day and make purchases. Thanks for any help! -
django create an api
Issue hi there, my application are almost frontend, what I meant by that, apps such as json formatter, codePen, jsFiddle and some online graphers, I wrote a lot of javascript to achieve a frontend interactive application. to be more focused, I have specific views, let's say, a markdown editor, that you can type from left, and outlook appearance render to right. here, it's a bit intricate, some user cases, when in a form, that the user can input raw text into a textarea, and it's markdown supported, therefore, I need to write a button, see in editor, which takes all user's current input text, and open a new tab with the markdown editor. The difficulty of this, is that those raw text do not need to be saved, the user only need to see the rendered effect, but django only works with model. I thought of many ways: rest framework api view Ajax POST view abstract model but I failed to make it work. Code template <!-- some code above --> {% comment %} form.content returns a string {% endcomment %} {{ form.content }} <button>see in editor</button> <!-- some code below --> javascript const content = document.querySelector('#id_content'); const button = … -
Django: How separate the data inside the model based on the user
I want to make an attendance system that prevents each user to see the attendance that some users have taken. But in my case, the attendance that the other users take can be shown by every user. How can I prevent this part? These are my codes: Models.py class ClassAttendance(models.Model):Faculty_Name = models.CharField(max_length=200, null=True, blank=True)Student_ID = models.CharField(max_length=200, null=True, blank=True)firstname = models.CharField(max_length=200, null=True, blank=True)lastname = models.CharField(max_length=200, null=True, blank=True)date = models.DateField(auto_now_add = True, null = True)time = models.TimeField(auto_now_add=True, null = True)college = models.CharField(max_length=200, null=True, blank=True)course = models.CharField(max_length=200, null=True, blank=True)year = models.CharField(max_length=200, null = True)section = models.CharField(max_length=200, null = True)subject = models.CharField(max_length=200, null = True)status = models.CharField(max_length=200, null = True, default='Absent')def __str__(self): return str(self.Student_ID + "_" + str(self.lastname) + "_" + str(self.date)+ "_" + str(self.subject)) class Faculty(models.Model): user = models.OneToOneField(User, null = True, blank = True, on_delete= models.CASCADE) firstname = models.CharField(max_length=200, null=True, blank=True) lastname = models.CharField(max_length=200, null=True, blank=True) college = models.CharField(max_length=200, null=True, choices=COLLEGE) course = models.CharField(max_length=200, null=True, choices=COURSE) year = models.CharField(max_length=200, null=True, choices=YEAR) section = models.CharField(max_length=200, null=True, choices=SECTION) subject = models.CharField(max_length=200, null=True, choices=SUBJECT) def str(self):return str(self.firstname + " " + self.lastname) class Meta:verbose_name_plural = "Faculties" I expected that after the users take attendance, they are the ones that can see that information -
Django UpdateView with reverse foreign key
I am using UpdateView, which is very cool abstraction and makes it very easy to update existing Models. I however want to include into this reverse foreign keys (kinda similar to inline admins). There is also inlineformset_factory, which helps creating this kind of reverse foreign key formsets. Of course I can handle all this manually (modelform and then each formset). But I'd like to put all those forms together and abstract this functionality into a view so that I then only specify the model, fields (same as in UpdateView), but also those reverse foreign keys. Is there a view for this or do I have to create my own? Any kind of experience with this would be appreciated. -
How to parse the "src" of image tag in Django textfield?
So I have code in my HTML template like this <div class="blog-content"> {{post.text|safe|linebreaks}} <p><img src="{{ image_dict.1.url }}" alt=""></p> </div> This above renders the image fine in HTML. My view is like this def post_detail(request, slug): post = BlogPost.objects.get(slug=slug) images = post.images.all() image_dict = {} for image in images: image_dict[image.image_order] = image.image print(image.image) return render(request, 'blog/post_detail.html', { 'post': post, 'images': images, 'image_dict': image_dict, }) Basically I'm setting it up so that I can render the images via {{image_dict.image_order.url}} But I wanna render the images as per following to associate them with each paragraph of text like so Text in Django TextField However, while the code within the template evaluates to the image url, for example say for an image with order '1' <p><img src="{{ image_dict.1.url }}" alt=""></p> becomes <p><img src="/media/images/codewithlewis.png" alt=""></p> The exact same code I typed in django's textfield (as attached in above image) remains like <p><img src="{{ image_dict.1.url }}" alt=""></p> within HTML and nothing gets rendered of course. A screen shot of this: I'm fairly new to Django but I feel like I have tried everything. How might I go about fixing this? Thank you. -
I'm getting the following error and I don't know what to do about it [closed]
since i'm new to django i don't know what to do next it'll really be helpful if somebody helped me i tried to inherit a template named 'basic.html' but at {% block css %}{% endblock %} i'm getting this error "{ expected css(css-lcurlyexpected)" -
Django testing HttpResponse
I've seen tutorials and guides about testing views which are rendering some templates, but I don't know how to use Django's testing module in case if I have views which are returning Jsons in HttpResponse? Any help will be appreciated. Thank You -
Refresh html DIv in Django
i am trying to refresh an {%extends%} page since my base.html is getting message information from whatever is happening in the python backend, it only shows the message after i refresh my page and i want to refresh it every x seconds so the alerts will show without needing to refresh my entire page. <div id="Mydiv"> {% extends 'crodlUSDT/base.html'%} </div> <script> $(document).ready(function() { function refresh() { var div = $('#Mydiv'), divHtml = div.html(); div.html(divHtml); } setInterval(function() { refresh() }, 3000); //300000 is 5minutes in ms }) </script> this is what i've found online but tested a lot of different things but none are working, is this possible ? thanks -
AttributeError: Class1 object has no attribute 'class2_set' with ManyToMany Field Django
Model : class Groupe(models.Model): name = models.CharField(max_length=255) autoAddingMail = models.CharField(max_length=255,null=True,blank=True) association = models.ForeignKey( User, limit_choices_to={'role': 'ASSOCIATION'}, null=False, on_delete=models.CASCADE, related_name='association' ) students = models.ManyToManyField( User, limit_choices_to={'role': 'STUDENT'}, related_name='students' ) events = models.ManyToManyField( Event ) class Meta: unique_together = ("name","association") REQUIRED_FIELDS = ['name','association'] def __str__(self): """ Return string representation of our user """ return self.name Unit test : groupe = event.groupe_set.get(name="name",association=association) <= works fine groupe = student.groupe_set.get(name="name",association=association) <= doesn't work The error : AttributeError: 'User' object has no attribute 'groupe_set' I don't get why student doesn't have the attribute groupe_set but event have it I have read the documentation about ManyToMany Fields but I didn't find answers. -
How to save http request to django?
I have a device that do some calculations and then i want to send it with help of request to my site: import requests params = {'data1': '47237582'} r =requests.get("http://127.0.0.1:8000/", data = params) print(r) I have a django site. How can i save the value of my request for later display? def read(request): if request.method == 'GET': msg = request.GET['data1'] And how can i save it to database? -
Django Celery Beat - Runaway Process on Ubuntu
I have celerybeat running as a service on ubuntu. Generally speaking, everything works great. I have the same setup on numerous servers. Last night, I noticed the frequency at which a certain task was firing was doubled; seemingly out of the blue. In order to troubleshoot I did a few things: cleared the redis server + celery message queues restarted the celerybeat service restarted the redis-server service When those did not change the behavior, I tried: rebooting the server stopping the celerybeat service stopping the redis-server service Even after a reboot and having all the services stopped, the task is still being triggered! I have never encountered this kind of behavior before. How can the task continue to be triggered even without a messaging service? Any help or troubleshooting ideas here would be really appreciated. Thanks in advance. -
Why Django is the best Web Framework? [closed]
Django is the Best web framework for python based aplication. I want to know why it is best for design and developing web applications? -
Creating a custom User model by extending AbstractBaseUser
I am trying to create a custom User(CustomUser) by extending AbstractBaseUser. I am trying to remove username field and use email for authentication.I have not done the first migration yet. Here is models.py from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.core.mail import send_mail from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .managers import UserManager class CustomUser(AbstractBaseUser, PermissionsMixin): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. email and password are required. Other fields are optional. """ first_name = models.CharField(_("first name"), max_length=150, blank=True) last_name = models.CharField(_("last name"), max_length=150, blank=True) email = models.EmailField(_("email address"), unique=True) is_staff = models.BooleanField( _("staff status"), default=False, help_text=_("Designates whether the user can log into this admin site."), ) is_active = models.BooleanField( _("active"), default=True, help_text=_( "Designates whether this user should be treated as active. " "Unselect this instead of deleting accounts." ), ) date_joined = models.DateTimeField(_("date joined"), default=timezone.now) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["email"] class Meta: verbose_name = _("user") verbose_name_plural = _("users") abstract = True def clean(self): super().clean() self.email = self.__class__.objects.normalize_email(self.email) def get_full_name(self): """ Return the first_name plus the last_name, with a space in between. """ full_name = "%s %s" % (self.first_name, … -
Unable to Dynamically Render Django images on templates
So I've been trying to get the images uploaded through admin interface to render on a template but for some odd reason it just wont render the images. It renders any other type of data but NOT IMAGES. From Settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') From appvew.py: class ProjectsListView(ListView): model = Projects context_object_name = 'projects' template_name = 'myportfolio/portfolio.html' appurls.py: urlpatterns =[ path('home/', views.ProjectsListView.as_view()), # path('projects/', ) ] html template: {% load static %} </head> <body> <h1><p>This is my portfolio</p></h1> {% for project in projects %} <img src="{{project.screenshot}}" alt="No image found"> {% endfor %} </body> </html> output :( : I verified an old project of mine with pretty much the same set up and it works. This one on the other hand, only renders the name of the objects on other properties but not the images -
Django model F expression divide by zero error when calculating dynamic running total and average
I am using Django 3.2 I am dynamically calculating field values for an item that can be rated. Here is a snippet of my code: self.ratings_count = F('ratings_count') + 1 self.ratings_total = F('ratings_total') + rating_value self.ratings_average = F('ratings_total') / F('ratings_count') self.last_rated = timezone.now() self.save() # Divide by zero error here (no records exist in Db) I could trivially get around this by not using F fields (as a kludge). My question is - how do I implement the desired behaviour, whilst using F expressions? -
Versioning issues about Django project creation
My Django version is 2.2.12. When I use the command django-admin startproject mysite to create a project, this project's setting.py shows me that Generated by 'django-admin startproject' using Django 1.9.13. I typed the commandsudo pip freeze|grep -i 'django' into Pycharm's terminal to check the version and it also showed 2.2. This thing puzzled me. -
FastAPI, How to save image in a directory and get the image url for further access
I am trying to receive an image file via a POST method and save this image in a directory called profile_pictures And I was able to save the uploaded image. But now my problem is Now I want to show the image in the client side via an URL. So my concern is how should I generate the URL to access the image? I am new in back-end web technology so there is lack of knowledge so any broad answer or explanation will be helpful for me, thank you This is POST method @router.put("/upload/profile-picture") async def upload_profile_picture( profile_picture: UploadFile = File(...), db: Session = Depends(get_db), token_data: schemas.TokenData = Depends(oauth2.get_current_user), ): new_query = db.query(models.User).filter(token_data.id == models.User.id) x_user_data = new_query.first() # check whther user exist or not if not x_user_data: return HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="User not found", ) # save the file and get the saved path file_name = file_utils.save_profile_picture(profile_picture) return {"profile_picture": file_name} And this is the helper method from fileinput import filename from datetime import datetime import os from fastapi import File, UploadFile def save_file_and_return_path(profile_picture: UploadFile) -> str: try: os.mkdir("profile_pictures") print(f"current directory = {os.getcwd()}") except Exception as e: print(f"Exception 1 : {e}") file_name = ( f"{os.getcwd()}/profile_pictures/{profile_picture.filename.replace(' ', '_')}" ) with open(file_name, "wb+") … -
Create @login_required like function for used form(Modelform). So that User can't access confidential url without login-by typing just url?
I know that I can use @login_required but it is only used when we store user in User But in my case I stored model in form So it is not working for me. Also my created user is not getting authenticated when I use user.is_authenticated So I need custom login_required decorator which can be use to stop anyone from accessing direct url (confidential URl which are only accessed when you Login). forms.py class usrForm(forms.ModelForm): password = forms.CharField(initial=123) class Meta: model = Person fields = ('first_name','last_name','username','email','password','position') def __init__(self, *args, **kwargs): super(usrForm,self).__init__(*args,**kwargs) self.fields['position'].empty_label = "Select" class usrChange(forms.ModelForm): class Meta: model = Person fields = ('username','password') widgets= { 'password' : forms.PasswordInput(), } class loginForm(forms.ModelForm): class Meta: model = Person fields = ('username','password') widgets= { 'password' : forms.PasswordInput(), } models.py class Position(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title class Person(models.Model): first_name = models.CharField(max_length=50,default='') last_name = models.CharField(max_length=50,default='') username = models.CharField(max_length=50,default='') password = models.CharField(max_length=50,default='') email = models.EmailField(max_length=50) position = models.ForeignKey(Position, on_delete=models.CASCADE) def __str__(self): return self.username views.py def user_list(request): context = {'user_list' : Person.objects.all()} return render(request, "usr_list.html", context) def user_chnged_list(request): form = usrForm(request.POST) if form.is_valid(): form.save() context = {'user_list' : Person.objects.all()} return render(request, "usr_list.html", context) def user_form(request, id=0): if request.method == "GET": if id ==0: … -
Using User object and AllAuth together in a Django application
My model has a User class subclassed from AbstractUser (so i am reusing all default fields of the abstractuser object). I have been using this for a while and then I thought of using all-auth django for extra functionality. We set it up and everything works as it should. However I have some confusions with the new tables these models are creating. I still have the original user table which was storing email, password and some other default information (form the Abstract user) I now have a few more account_ tables (from allauth). One of these tables, account_emailaddress also stores the email as information. Im a bit confused on why I need to store the email two times ? Once in the user table and another time in the account_emailaddress table. We can also this using a link from User to email address table (or from User model to allauth model somehow). -
Django - json.decoder.JSONDecodeError: Expecting value: line 1 column 1
I am trying to parse post request body in Django if request.method == 'POST': data = json.loads(request.body.decode()) obj = Person( name = data.get('name'), last_name = data.get('last_name'), birth_date = data.get('birth_date'), age = data.get('age') ) obj.save() I get the next error : json.decoder.JSONDecodeError: Expecting value: line 1 column 1 I tried to use data = json.loads(request.body.decode('uft-8')) but the error is same. any ideas how I can fix the problem? -
'QuerySet' object has no attribute 'pk' in "bulk_update"
I have model of Professor and need to "bulk_update". I have to do this in 2 requests from my DB. But i have exception ('QuerySet' object has no attribute 'pk'). If i use get i have another exception(get() returned more than one Professor). My model. class Professor(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) age = models.IntegerField(default=18) class Meta: indexes = [models.Index(fields=['first_name'])] My code def update_professor_first_names(first_name_updates: List[NameUpdate]): prof_id = [id for id, name in first_name_updates] prof = Professor.objects.filter(id__in=prof_id) tmp = [] for prof_id, new_first_name in first_name_updates: prof.first_name = new_first_name tmp.append(prof) Professor.objects.bulk_update(tmp, ['first_name']) Can you give me some advices about it?