Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am learning django, how to change function to class in the views.py
How to change function to class in the views.py I want to change the view to something like this: https://docs.djangoproject.com/en/dev/ref/class-based-views/generic-editing/#createview class NewTopic(CreateView): model = Topic fields = ['title', 'category', 'author', 'text'] template_name = 'app_a/new_category.html' This is not correct, i want to modify it. models.py class Category(models.Model): title = models.CharField(max_length=200, default='') author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(default=localtime) def __str__(self): return self.title class Topic(models.Model): title = models.CharField(max_length=200, default='') category = models.ForeignKey(Category, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(default='') date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title views.py def new_topic(request, pk): category = Category.objects.get(pk=pk) if request.method == 'POST': form = TopicForm(data=request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.author = request.user new_topic.category = category new_topic.save() form.save_m2m() return HttpResponseRedirect(reverse('app:category', args=[pk])) else: return render(request, 'app/index.html') context = {'category': category, 'form': form} return render(request, 'app/new_topic.html', context) forms.py class CategoryForm(forms.ModelForm): class Meta: model = Category fields = ['title', 'author'] class TopicForm(forms.ModelForm): text = forms.CharField(widget=forms.Textarea(attrs={"rows":5,'cols': 50})) class Meta: model = Topic fields = ['title', 'category', 'author', 'text'] urls.py urlpatterns = [ re_path(r'^new_topic/(?P<pk>\d+)/$', views.new_topic, name='new_topic'), ] I don't know how to modify it, thank you! -
how to make form Sub heading using django form
I want to make subfields in Django enter image description here -
Django after migration UndefinedColumn error in production
I have a website in production. I have an app, with a model. It contained a markdown_file attribute: markdown_file=models.FileField(upload_to='/media/') But since the number of file is limited, I decided to make it a markdown_filename attribute with a choices selection box: markdown_filename=models.CharField(max_length=30,null=True,blank=True,choices=MENU_MARKDOWN_FILE_CHOICES) Therefore, I modified this model and made migrations locally. I pushed the code in production and run: python manage.py migrate After I checked with showmigrations and sqlmigrate, that the modification I made were there. Then, I checked in the database, that the fields were correctly modified. But, I still get this error, when trying to access the website: ERROR:django.request:Internal Server Error: / Traceback (most recent call last): File "/srv/data/web/vhosts/default/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column showcase_subpage.markdown_file does not exist LINE 1: ...bpage"."slug", "showcase_subpage"."html_content", "showcase_... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/srv/data/web/vhosts/default/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/srv/data/web/vhosts/default/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/srv/data/web/vhosts/default/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./showcase/views.py", line 10, in home return render(request, 'showcase/home.html', context) File "/srv/data/web/vhosts/default/local/lib/python3.7/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/srv/data/web/vhosts/default/local/lib/python3.7/site-packages/django/template/loader.py", line … -
Trying to display loop on new line python
I am trying to get the following code to output to a new line each time. However, when I view on the webpage, it doesn't output as expected. I have tried \n and || in the code if (form.getvalue("username")=="$username"): self.wfile.write("Table: Users \n") self.wfile.write("Username | Password\n") self.wfile.write("test") Output: Table: Users Username|Password test I don,t receive any errors -
Django URL Page error when link is clicked twice
I have a url defined as: path("home/projects/",project_view,name = "viewProject") This render correctly when i click on the 'Details' link on project_view.html <li> <a href="projects" data-toggle="tooltip" class="tip-bottom" title="All Projects"> <i class="fa fa-list" aria-hidden="true">Details</i></a> </li> But while i am on the same page,if i click the same link again i get an error: home/projects/ [name='viewProject'] "Page not found...The current path, home/projects/projects, didn't match any of these" I understand what the error means,but how can i redirect the page to "home/projects/" if the link is clicked twice? -
Performing two actions with one form in django
Here I am trying to perform two actions deleting or sending email to selected users.For sending emails a form will be required so I stored checked users in a session like this and after sending email i am removing all the users from session with session['users'].clear(). But neither it throws any errors nor it sends the email it just renders the send_mail_selected template. What's wrong with this code? Deleting the selected users working fine def selected_users(request): form = SendMailForm() selected_users = get_user_model().objects.filter(id__in=request.POST.getlist('users')) initial = {'users':[]} session = request.session.get('users',initial) if selected_users: for user in selected_users: if not user in session['users']: session['users'].append(user.email) print('hello1',session['users']) if selected_users and request.method == 'POST' and 'delete_selected' in request.POST: count = selected_users.count() selected_users.delete() messages.success(request, '{} users deleted.'.format(count)) return redirect('view_users') elif request.method == 'POST' and 'mail_selected' in request.POST: form = SendMailForm(request.POST or None) config = EmailConfiguration.objects.order_by('-date').first() backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user, password=config.email_host_password, use_tls=config.email_use_tls) if form.is_valid(): sub = form.cleaned_data['sub'] msg = form.cleaned_data['msg'] for email in session['users']: email = EmailMessage(subject=sub, body=msg, from_email=config.email_host_user, to=[email], connection=backend) email.send() # clearing users from session after email sends session['users'].clear() messages.success(request, 'Your mail sent.') return redirect('view_users') else: print(form.errors) return render(request, 'send_mail_selected.html', {'users': selected_users,'form':form,'session':session}) -
Frontend and backend languages
I'm currently planificating a web development for statistical analysis of big data of social media. I'm looking for some advice for good frontend and backend languages. For backend i'm pretty sure i'll use Django, because python has a great capability for big data analysis but i'm lost in frontend languages. I've seen some people that recommend going with JS, some people just stick to Django. Can you please give me some advice on this frontend languages, in which case should i use it and why? -
Generating multiple objects with random start and end dates which NEVER overlap?
I'm creating 20 random objects for my fixtures like this: EVENT_TYPE = [ 'A', 'B', 'C', ] for _ in range(20): start_date = get_random_date(date(date.today().year, 1, 1), now()) Event.objects.create( category=random.choice(EVENT_TYPE), start=start_date, end=get_random_date(start_date, start_date + timedelta(days=180)), ) What I want to do: having 20 objects with "unique" date ranges. For example Object1 starts at 01.01.2019 and ends at 10.01.2019 and has an EVENT_TYPE of "A". So no other object created should have a date range between those two dates with the same EVENT_TYPE. They can have a start date at 10.01.2019 or an end date at 01.01.2019, but never something between those dates. BUT as you can see my objects also have categories, which split them, so if obj1 and obj2 have the same date range, but a different EVENT_TYPE thats totally okay. Right now my code does that totally random. I tried to figure out a way to achieve that, but just couldn't come up with a smart idea. Does someone know a clever solution to this problem? How could I check if one object is in between the date range of another and let say just change its date to the beginning or end of that object so that it … -
Django import: Ignore created value from TimeStampedModel
I have a model which is inherited from TimeStampedModel and I am trying to import data using Django import_export. The imported data contains "created" column providing the datetime values which are different from current date time. The import is successful but it is using the created value from TimeStampedModel rather that the one from the file. Is there anything that can be done in the import_obj function to override the created value from the TimeStampedModel? The format of date time in the file is in the expected format and is one of the supported formats. class TestResource(resources.ModelResource): class Meta: model = MyModel def import_obj(self, obj, data, dry_run): for field in self.get_fields(): self.import_field(field, obj, data) Object creation date is always the current datetime rather than the datetime in the imported file. -
rest_framework.exceptions.ParseError: JSON parse error - Invalid control character
I'm trying to create a decrypting API. But when i pass a encrypted data as string it return this error. However if i escape the next line characters it will work. This is the non-formatted message, and i can expect it only in this format. (Details changed) { "passphrase": "not_passphrase", "message": "-----BEGIN PGP MESSAGE----- Version: GnuPG v2 jA0ECQMCVady3XMDJV3X0kcBF+zdkfZOMhISoYBRwR3uk3vNv+TEg+rJnp4/yYIS pEoI2S82cDiCNBIVAYWB8WKPtH2R2YSussKhpSJ4mFgqyOA01uwroA== =KvJQ -----END PGP MESSAGE-----" } I am using Django Rest framework. I'm not that deeply familiar with the settings process. I've done up a lot of reading including STRICT_JSON and UNICODE however i was not able to achieve a working solution. Any guidance is appreciated. -
Convert request.get and request.post data to dictionary
I'm trying to convert request.GET and request.POST to dictionary I tried doing request.GET.dict() and json.dumps(request.GET). somehow it returns dict like structure. for eg: {'name': 'abc'}, but type of this dict is str -
Django multiprocessing database concurrency
I am stuck with the following database concurrency problem. I am building a django webapp using psycopg2 to comunicate with a PostgreSQL database. The queries are run from different processes. In order to lock rows all the queries are inside a transaction atomic block. with transaction.atomic(): self.analysis_obj = Analysis.objects.select_for_update().get(pk=self.analysis_id) However sometimes I get random error like: 'no results to fetch', 'pop from empty list', 'error with status PGRES_TUPLES_OK and no message from the libpq'. Any idea to deal with this problem? Many thanks. -
when i click a images then show 3 images on other html page but these 3 images is different for every clicked images
i want to access related class object through value class because img field of value class relates with 3 images of related class by Foreign Key this is my models.py class value(models.Model): img = models.ImageField(upload_to='images/') price = models.IntegerField() class related(models.Model): u_id = models.ForeignKey(value,on_delete=models.CASCADE) image=models.ImageField(upload_to='images/') loc = models.CharField(max_length=20) this my views.py def home(request): rels = value.objects return render(request,'rel/home.html',{'rels':rels}) def detail(request,id): det = get_object_or_404(value,pk=id) det1 = det.id u_id = related.objects.get() return render(request,'rel/detail.html',{'det':det,'u_id':u_id}) this my html page {% for u in u_id.all %} <div class="container"> <img src="{{ u_id.image.url }}" alt=""> </div> {% endfor %} get() returned more than one related -- it returned 3! (on browser window ) i want that when i click a image which is available on my home.html then show 3 images on other html page but condition is that these 3 images is different for every images which is available on home.html -
how to fix Form validation 'unknow' in django
When I use single form there is no problem but when I used multi-forms in a class based view it's getting validation failed with image field. I tried to fix with previous solution provided in stack overflow but couldn't able to solve it. views.py codes in views class ProfileEditView(View): profile_class = ProfileForm profile_image_class = ProfileImageForm template_name = 'user/profile_edit.html' def get(self,request,pk): if pk: user = User.objects.get(pk=pk) profile = Profile.objects.get(user = user) profile_image = ProfileImage.objects.get(user = user) profile_form = self.profile_class(instance = profile) profile_image_form = self.profile_image_class(instance = profile_image) context = { 'profile_form':profile_form, 'profile_image_form':profile_image_form } return render(request, self.template_name, context) else: profile_form = self.profile_class(None) profile_image_form = self.profile_image_class(None) context = { 'profile_form':profile_form, 'profile_image_form':profile_image_form } return render(request, self.template_name, context) def post(self,request,pk=None, **kwargs): profile_form = self.profile_class(request.POST,instance=Profile()) profile_image_form = self.profile_image_class(request.POST,instance=ProfileImage()) if profile_image_form.is_valid(): #and profile_image_form.is_valid(): profile = profile_form.save(commit=False) profile_image = profile_image_form.save(commit=False) profile.user = self.request.user profile_image.user = self.request.user profile.save() profile_image.save() return redirect('music:album_list') context = { 'profile_form':profile_form, 'profile_image_form':profile_image_form, 'error_message':'Something went wrong', } return render(request, self.template_name, context) models.py codes in model def get_profile_upload_to(instance,filename): new_filename = '{}.{}'.format(uuid4,filename.split('.')[-1]) return "profile/{}/{}".format(instance.user.id, new_filename) class ProfileImage(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(upload_to=get_profile_upload_to) uploaded = models.DateTimeField(auto_now=True) class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) bio = models.TextField(max_length=500,null=True, blank=True) location = models.CharField(max_length=50,null=True, blank=True) birth_date = models.DateField(null=True, blank=True) email_confirmed = models.BooleanField(default=False) form.py codes in … -
i didn't understand about an error saying Runtime error:Model class travello.models.Destination doesn't declare an explicit app_label
INSTALLED_APPS = [ 'travello.apps.TravelloConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] i am getting, RuntimeError:Model class travello.models.Destination doesn't declare an explicit app_label and isn't in an Installed_Apps the python is screenshooted in below -
How to write a query for retrieving matching book-instances?
I need to make a filter to show BookInstances with following conditions: BookInstance.public = True BookInstance.owner != current logged in user BookInstance.book.title like %some text% BookInstance.book.description like %some text% BookInstance.book.authors(id_in=some list of ids) BookInstance.book.categories(id_in=some list of ids) The conditions will be combined as: 1 AND 2 AND ( ( 3 OR 4 ) OR 5 OR 6 ) 3 & 4 use same text for search. current scaffolding in view: searchedObjects = BookInstance.objects; filterObj = dict(request.POST) for key in filterObj: if key == 'bookTitleOrDescription': #condition 3 and 4 bookTitleOrDescription = filterObj[key][0] elif key == 'author[]': # condition 5 authorList = filterObj[key] elif key == 'category[]': # condition 6 categoryList = filterObj[key] searchedObjects will have the query result. models: class Author(SafeDeleteModel): name = models.CharField(max_length=255) class Category(SafeDeleteModel): title = models.CharField(max_length=255) class Book(SafeDeleteModel): title = models.CharField(max_length=255) description = models.CharField(max_length=255) authors = models.ManyToManyField(Author) categories = models.ManyToManyField(Category) class BookInstance(SafeDeleteModel): owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) book = models.ForeignKey(Book, on_delete=models.CASCADE) public = models.BooleanField(verbose_name='Will show in search ?') lendable = models.BooleanField(verbose_name='In good condition ?') -
How to get average from each hour in one week in django?
I have a task to get the average some data in each hour inside a week. {'hour': 0, 'count': 70} {'hour': 1, 'count': 92} {'hour': 2, 'count': 94} {'hour': 3, 'count': 88} {'hour': 4, 'count': 68} {'hour': 5, 'count': 69} {'hour': 6, 'count': 70} {'hour': 7, 'count': 82} {'hour': 8, 'count': 91} {'hour': 9, 'count': 67} {'hour': 10, 'count': 92} {'hour': 11, 'count': 100} {'hour': 12, 'count': 92} {'hour': 13, 'count': 55} {'hour': 14, 'count': 61} {'hour': 15, 'count': 47} {'hour': 16, 'count': 36} {'hour': 17, 'count': 19} {'hour': 18, 'count': 11} {'hour': 19, 'count': 6} {'hour': 20, 'count': 3} {'hour': 21, 'count': 9} {'hour': 22, 'count': 27} {'hour': 23, 'count': 47} The data above is the result of this query result = Device.objects.filter(station__in=stations, created_at__range=(start_date, end_date)) \ .extra({'hour': 'hour(created_at)'}) \ .values('hour').annotate(count=Count('id')).order_by('hour') the result is queryed by 7 days range, what I want to do is get the average for each hour in 7 days, exampe the total of count in hour 0 is 70 then i need to average it from 7 days. Any suggestion? -
'RelatedManager' object is not subscriptable
thanks for your time. i'm trying to get the first images of a foreignKey image model and display with the other fields i've read some questions and docs about related models and the best i got was to create a function on my models to call it after just to get the first image. models.py: class Veiculos (models.Model): YEAR_CHOICES = [] for r in range(1960, (datetime.now().year+1)): YEAR_CHOICES.append((r, r)) modelo = models.CharField(max_length=100) potencia = models.CharField(max_length=40) cor = models.CharField(max_length=30) preco = models.DecimalField(max_digits=8, decimal_places=2) ano = models.IntegerField(('ano'), choices=YEAR_CHOICES, default=datetime.now().year) category = models.ManyToManyField('Categorias') created_time = models.DateTimeField(auto_now=True) updated_time = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s %s' % (self.modelo, self.preco) def get_absolute_url(self): return reverse('category2') def first_image(self): return self.images[0] def get_image_filename(instance, filename): modelo = instance.veicle.modelo slug = slugify(modelo) return "veiculos_imagens/%s-%s" % (slug, filename) class Imagens (models.Model): veicle = models.ForeignKey(Veiculos, default=None, on_delete=models.CASCADE, related_name='images') imagem = models.ImageField(upload_to=get_image_filename) views.py: def amp_category(request): queryset = Veiculos.objects.all() return render(request, 'amp/category.amp.html', {'veiculos': queryset}) category.amp.html: {% extends "amp/base.amp.html" %} {% block tittle %} <title>ok</title>{% endblock tittle %} {% block content %} <body> <h1>ok</h1> {% for veiculo in veiculos %} <h2>{{veiculo.modelo}}</h2> <amp-img src="{{ veiculo.first_image.src }}" alt="" width="300" height="340"></amp-img> {% endfor %} </body> {% endblock %} </html> thats the error that i'm getting: hava i set related_name wrong … -
registration form with profilepicture by using django
registration form with userid,username,useremail,userlocation,profilepicture,password1'password2 and login page with userid,password after login it will show total registration mumbers with photo and name.by using django -
How to add new fields to users according to its group (role) in Django
I'm trying to do a logistics web application in Django and I need to assign different roles to the users. I have normal users (clients), employees (office employees, delivery man, truck drivers...) and supervisors. I need to do the following: Office employees and delivery man users: need to have an office assigned Truck drivers users: need to have an assigned route I've made 2 models (Offices and Routes) but I don't know how to relate the users with these models. I've read websites that create custom classes inherited from AbstractBaseUser or AbstractUser, but I don't know how to do it with this special case. I hope to hear the right answer here. Thanks in advance! -
I created a form in Django from the model attributes ! but I did not find anything to customize this form ! I have to change it's design
I created a form from the model attributes ! but I did not find anything to customize this form ! I have to change it's design ! This is my form -
Heroku build error - ERROR in Entry module not found
I'm deploying my Django react app to Heroku, but Terminal Error Server Error package.json & webpack.config.js -
Download (powerpoint) - file with django REST framework
I am running a django app and I want to be able to download a powerpoint file with an API call using django REST framework and the library requests. My model is very simple: class FileCollection(models.Model): name = models.CharField(max_length=120, null=True, blank=True) store_file = models.FileField(upload_to='file_storage_api/', null=True, blank=True) creation_date = models.DateTimeField(null=True, blank=True) Then in my view I want to query different instances of the FileCollection model which I then want to download. First I tried just calling the link but my upload files should be private that's why I would like to use token authentication that I already have implemented. I also tried following this answer but https://stackoverflow.com/questions/38697529/ but can't get it to work. I also read the REST doc on Renderers but I don't really get how to implement them. Is there any (easy) way of a downloading a powerpoint file with REST and requests? Any help is very much appreciated, thanks very much in advance! -
when I click on next on pagination all previous query parameter are lost in django
I have a list page for ads. There are two search forms with multiples parameters as well as pagination. When I click on next on the pagination bar, the following error shows up: UnboundLocalError at /towns/results/ local variable 'post_city' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/towns/results/?page=2& Django Version: 1.11.4 Exception Type: UnboundLocalError Exception Value: local variable 'post_city' referenced before assignment Exception Location: /Users/engsalehalomari/Desktop/try/try/try/salehslist/towns/views.py in search, line 615 Python Executable: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 Python Version: 3.6.5 I have two functions one to view the listing page and the other one to conduct the search. There are three parameters passed to listing page "post city, category, and subcategory". These parameters are also passed with other search parameter. When I load the page, everything works fine, the only problem is when I click on icon " link" next on pagination bar. It gives the previous error. It seems to me that the search parameters from the search result is lost. Please help me to resolve this issue. the two views functions are: def list_page(request, post_city, category_name, sub_category_name): template = 'towns/salehslist/list_page.html' query_fc = post_city query_fcc = category_name query_fsc = sub_category_name all_p_cities = City.objects.filter(province_name__country_id__country_name__iexact='united states') all_p_categories = Post_Category.objects.all() all_p_sub_category = Post_Sub_Category.objects.all() context = { "post_city":post_city, … -
How to create a form and view consist of nested formset
I'm creating a form to add a company consist of many formsets such as phone, mobile, whatsapp and employeee. The employee formset is nested. it has some formsets too such as phone, mobile, whatsapp, and ... . I need some help to create this form, view and template. Is it possible to use Django formsets or I should try another way