Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To Click A Link Within An Email
Im testing my website with Selenium. After a user registers, they must click a link emailed to them in order to log in. I am able to get the email, but do not know how to click the link. This selects the email confirmation_email = mail.outbox[0] Now I just need to find a link within it and press it. The email link will be something like: http://localhost:52348/accounts/confirm-email/MQ:1jfhcf:4ZqeOcmY4fdfh1lhA0feBl7eeUBk3440/ Thank you. -
why my django slug is not working properly
I want to allow user to search in database for the topic. and show the topic name in url. I already created slug field in database but when i am trying to fetch the data from the database the url is not showing correctly. url is showing: http://127.0.0.1:8000/topic/<slug:topicname>/ what I want to show: http://127.0.0.1:8000/topic/introduction-to-python/ My urls.py file from django.urls import path from . import views urlpatterns = [ path('', views.apphome), path('topic/<slug:topicname>/', views.searchtopic, name = 'searchtopic'), ] My model for the project class blogposts(models.Model): topic = models.CharField(max_length = 200) slug = models.SlugField(max_length = 150, null=True, blank = True) post = models.TextField(max_length = 500) def __str__(self): return self.topic This is my view def searchtopic(request,topicname): if request.method == 'POST': topicname = request.POST.get('searchtopicname') mypost = mypostlist.objects.filter(slug = topicname) context = { 'mypost':mypost, } return render(request, 'blog/result.html',context) My form for searching topic <form action="topic/<slug:topicname>/" method="POST"> {% csrf_token %} <input type="search" placeholder="Search topics or keywords" name="searchtopicname"> <button type="submit">Search</button> </form> -
How to know the Project name when we have multiple applications in django project
I have recently got added into a new project in django hired by a company, They have nearly 38 folders in same directory that of manage.py and have also changed the folder name in which manage.py is situated . Is there any way to know which folder is the main project ?? -
Can anyone tell me why I am getting error.(django&people API)
I was following this documentation to get people name in a Gmail id. I am not getting an authorization window to authenticate the Gmail account. https://developers.google.com/people I provided the client id and secret key. from django.shortcuts import render from inviteapp.forms import InviteForm import httplib2 from apiclient.discovery import build from oauth2client.file import Storage from oauth2client.client import OAuth2WebServerFlow from oauth2client.tools import run_flow def index(request): if(request.method=="POST"): email='' invite=InviteForm(data=request.POST) if invite.is_valid(): email=invite.cleaned_data['email'] # Set up a Flow object to be used if we need to authenticate. This # sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with # the information it needs to authenticate. Note that it is called # the Web Server Flow, but it can also handle the flow for # installed applications. # # Go to the Google API Console, open your application's # credentials page, and copy the client ID and client secret. # Then paste them into the following code. FLOW = OAuth2WebServerFlow( client_id='xxxx', client_secret='xxx', scope='https://www.googleapis.com/auth/contacts.readonly', user_agent='xxx') # If the Credentials don't exist or are invalid, run through the # installed application flow. The Storage object will ensure that, # if successful, the good Credentials will get written back to a # file. storage = Storage('info.dat') credentials … -
how to set extra fields in django inlineformset dynamically
i'm working on a projects for a mobile store which working with IMEI of mobiles each single mobile has its own imei , and the owner of the store selling phone depend on its IMEI's , now when the admin add new mobile in MobileStorage for example quantity= 20 mobile iphone11X have 20 different IMEI's , i want to allow the admin whenever he add new mobile and then select the quantities (20) then extra fields will be 20 , if he filled 10 in quantity field extra fields for IMEI will be 10 class MobileStorage(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE) imei = models.ForeignKey(Imei,on_delete=models.CASCADE,verbose_name='IMEI') quantity = models.PositiveIntegerField() class Imei(models.Model): imei = models.CharField(max_length=50,verbose_name='IMEI',unique=True) class Mobile(models.Model): mobile = models.CharField(max_length=50,unique=True) my forms.py class MobileStorageForm(forms.ModelForm): mobile = forms.ModelChoiceField(queryset=Mobile.objects.all(),empty_label='') class Meta: model = MobileStorage fields = [ 'mobile','quantity' ] class ImeiForm(forms.ModelForm): class Meta: model = Imei fields = ['imei'] i want to control extra fields depend on the quantity in MobileStorage model , and the create for example 20 instance in Imei model MobileStorageFormInlineSet = inlineformset_factory( MobileStorage,Imei,form=ImeiForm,fields=('imei'),extra=2,can_delete=False ) anyone have an idea i appreciate it -
cached_property and classmethod doesnt work together, Django
I am trying to use cached_property and classmethod decorators together in a viewset but it doesnt work regardless of their mutual position. Is it any chance to make it work together or cached_property doesnt work with classmethod? Tnanks. @cached_property @classmethod def get_child_extra_actions(cls): """ Returns only extra actions defined in this exact viewset exclude actions defined in superclasses. """ all_extra_actions = cls.get_extra_actions() parent_extra_actions = cls.__base__.get_extra_actions() child_extra_actions = set(all_extra_actions).difference(parent_extra_actions) return (act.__name__ for act in child_extra_actions) -
There is a problem distributing django using heroku
Now I enter heroku create git push heroku master heroku run python manage.py migrate heroku run python manage.py createsuperuser heroku open I had error enter image description here How can I solve this problem? My github url is https://github.com/chea-young/local_library -
django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
I've just moved my project which was running perfectly in windows to centos 7. I've all the required dependencies installed in virtual environment and have mysql database running at http://localhost/phpmyadmin, using xampp. however, python manage.py runserver throws me following error : django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)") also systemctl status mysqld throws following error (myvenv) [root@CIPL-5PC226 django-project]# systemctl status mysqld ● mysqld.service - MySQL Server Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled) Active: deactivating (stop-sigterm) (Result: exit-code) Docs: man:mysqld(8) http://dev.mysql.com/doc/refman/en/using-systemd.html Process: 11595 ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid $MYSQLD_OPTS (code=exited, status=1/FAILURE) Process: 11572 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS) Tasks: 23 CGroup: /system.slice/mysqld.service └─11598 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid Jun 01 14:24:17 ABCD-5PC226 systemd[1]: Starting MySQL Server... Jun 01 14:24:18 ABCD-5PC226 mysqld[11595]: Initialization of mysqld failed: 0 Jun 01 14:24:18 ABCD-5PC226 systemd[1]: mysqld.service: control process exited, code=exited status=1 because of my limited knowledge of centos, despite searching and trying out multiple solutions, I've not been able to resolve the issue yet. my understanding is that i have sql running at localhost/xampp but due to some reason the project is not able to connect despite clearly mentioned in the database section of settings.py file of django project. -
How to set DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings? Time to give up with this?? :(
I am really with Django and I am getting a little bit crazy with this issue. I created a new project and app in Django, runserver without problems, but if I ran : django-admin check Im gettin this error: ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LANGUAGE_CODE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried to solved with differents solutions proposed but none of them worked (probably bad execution by me, idk). Really hope you can help me guys! Thanks in advance, Best. Example of similar error than mine, that i took from here ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings The answer proposed is: export DJANGO_SETTINGS_MODULE=mysite.settings I tried set DJANGO_SETTINGS_MODULE=mysite.settings with my app name instead of "mysite" in my app folder but it does not work... 22:46:15 web.1 | Traceback (most recent call last): 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/gunicorn/arbiter.py", line 495, in spawn_worker 22:46:15 web.1 | worker.init_process() 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/gunicorn/workers/base.py", line 106, in init_process 22:46:15 web.1 | self.wsgi = self.app.wsgi() 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/gunicorn/app/base.py", line 114, in wsgi 22:46:15 web.1 | self.callable = self.load() 22:46:15 web.1 | File … -
Django modelforms attrs not passed to template
In Django3 I have a modelform, and I want to add some styling to the rendered form Here is the model: class Inschrijf(models.Model): naam = models.CharField(max_length=100) This is the form: class InschrijfForm(ModelForm): class Meta: model = Inschrijf fields = ('naam',) wigets = { 'naam': TextInput(attrs={'class':'form-control','required': 'required','placeholder': 'Naam contact persoon'}), } labels = { 'naam': 'Contact persoon', } error_messages = { 'naam': { 'required': 'Vul uw naam in' } } This is rendered as: <p><label for="id_naam">Contact persoon:</label> <input type="text" name="naam" maxlength="100" required id="id_naam"></p> The custom label is passed to the template, but the widgets part not -
How get products from product table based on the category search in django restframework, How do inner join in django restframework
I am very much new in django restframework,I tried to create a search api. I have 2 models designed class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): product_name = models.CharField(max_length=255) product_Comments = models.CharField(max_length=255) size = models.CharField(max_length=10, null=True) product_Status = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) def __str__(self): return self.product_Description I want to create a rest API, in which I can search the category and based on the search i want to list the product which related to that category. How can I do it. -
Python Django Make Migrations Bug, always trying to delete
Whenever I run the makemigration command it always generate a delete script: Generated by Django 3.0.6 on 2020-06-01 23:28 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('chat', '0001_initial'), ] operations = [ migrations.DeleteModel( name='MessageModel', ), ] I am not trying to delete the model. So I try to run the migrate, then the model gets delteted from mysql. Then I try to make changes to model and ru nmakemigrations but it cannot detect any change. So I delete the makemigrations manually but everytime I run it again it delete the model from database.. i spent hours but can't figure out why -
Django with Djongo, EmbeddedFields returns Models aren't loaded yet
I have a new Django project setup. I have only one package installed Djongo. And i have a local MongoDB running. If I write a simple model with just CharFields in models.py in my app the migration works fine. But when I use EmbeddedFields it returns an error. I've copied the code from the Djongo documentation to test with code that should work. Code Source This is what I have in my models.py: from djongo import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Meta: abstract = True class Entry(models.Model): _id = models.ObjectIdField() blog = models.EmbeddedField( model_container=Blog ) headline = models.CharField(max_length=255) objects = models.DjongoManager() Error message when running py manage.py makemigrations File "C:\Users\FelixEklöf\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 178, in get_models self.check_models_ready() File "C:\Users\FelixEklöf\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 140, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
Is there any way to force django run some finishing code before exit?
I am running a server program with django, I want to run some code before and after the server running. Where can I put those code? <run function a here> Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ^C <run function b here> -
Post() got an unexpected keyword argument 'user'
views.py Post() got an unexpected keyword argument 'user' so how i solve this error def post(request): if request.method=="POST": Image=request.FILES['image'] caption=request.POST.get('ta','') userr=request.user post_obj=Post(user=userr,image=Image,caption=caption) print(userr,Image,caption,end='\n') post_obj.save() models.py from django.db import models from django.contrib.auth.models import User # # Create your models here. from django.db import models # # # Create your models here. class Post(models.Model): userr = models.ForeignKey(User,on_delete=models.CASCADE) image=models.FileField(upload_to='media/',blank=True) caption = models.CharField(max_length=200,default="") timeStamp=models.DateTimeField(auto_now_add=True,blank=True,null=True) -
Django CSS changes are not applied
I am new to Django and I am using a CSS file for my styles and for now the styles are applied to my html. Now I have created a new class: .post-image { height: 500px; width: 500px; } and have applied the class to the HTML element I want to style like this: <img class="post-image" src="{{ post.image.url }}" alt=""> But the class post-image does not apply somehow. When I change it back to the old class the image gets resized. Also when I tried to edit the old class in my main.css the changes were not applied. My main.css file is in my static directory and I have added the static directory in my settings.py file like this: STATIC_URL = '/static/' and I have imported the stylesheet in my base.html like this: <link rel="stylesheet" type="text/css" href="{% static 'feed/main.css' %}"> -
Guidance on Which Framework to use for app development
I am new to web and app development. I started with Django but I am facing difficulty in understanding the different functions they have made. Actually I am not able to understand the logic behind functions already defined . But my brother suggests me to just use them. So I am a bit confused if i have done right by starting with django framework. I know python, javascript,java. So should i shift to Node.Js or continue with django. -
How to render the values in a parent child relationship in Django
I am creating a django app where the admin can add travel packages. To add the explicit details of the package I created a child that will handle those values. Here is how the code looks like. class Category(models.Model): title = models.CharField(max_length=30) slug = models.SlugField(unique=True) class Meta: ordering = ['title'] def __str__(self): return self.title class SafariPackages(models.Model): image = models.ImageField(upload_to='SafariPackages/%Y/%m/%d', null=False) title = models.CharField(max_length=200) cost = models.FloatField(null=False) days = models.FloatField(blank=False, null=False) nights = models.FloatField(blank=False, null=False) category = models.ManyToManyField(Category) exodus = models.CharField(max_length=200) destination = models.CharField(max_length=200) telegram = models.TextField(max_length=140, null=False) description = models.TextField(null=False) slug = models.SlugField(max_length=200, unique=True) objects = EntryQuerySet.as_manager() def __str__(self): return self.title class Meta: verbose_name = 'Safari Package Entry' verbose_name_plural = 'Safari Package Entries' class DayNumber(models.Model): daydetails = models.ForeignKey(SafariPackages, related_name='daydetails', default=1, on_delete=models.CASCADE) day_number = models.CharField( max_length=10, null=True, blank=True) image = models.ImageField (upload_to='SafariPackagesDetails/%Y/%m/%d', null=False, default=1) day_description = models.TextField() The views that I have so far look like this def safaripackages_view(request, *args,**kwargs): print (args, kwargs) print (request.user) all_safaripackages = SafariPackages.objects.all() #Paginator paginator = Paginator(all_safaripackages, 8) page = request.GET.get('page') try: all_safaripackages = paginator.page(page) except PageNotAnInteger: all_safaripackages = paginator.page(1) except EmptyPage: all_safaripackages = paginator.page(paginator.num_pages) context = { 'all_safaripackages': all_safaripackages, } return render (request, "safaripackages.html", context) def single_safaripackage(request, post_id): safaripackage = SafariPackages.objects.get(pk=post_id) return render (request, 'single_safaripackage.html', … -
how to get value of this variable outside if loop in django template
{% define "color:green" as bcolor %} {% define "false" as wishl %} {% for i in wishlist %} {% if i.0 == itm.5 %} {% define "color:red" as bcolor %} {% define "true" as wish %} {{bcolor}} {% else %} {% define "color:green" as bcolor %} {{bcolor}} {% define "false" as wishl %} {% endif %} {% endfor %} {{bcolor}} <a class="text-center ml-auto "><center><i class="fa fa-heart fa-lg ml-auto "wishlist="{{wish}}" style="{{bcolor}};" id="wish" onclick="wishlist(this,{{forloop.counter}})" attrbute="" ></i></center></a> i want to get the value of the variable out side if condition,If the item id = wishlit .item id then change the bg color as red else green -
autoupdate the data from excel in django
I have imported data from excel file using ImportExportModelAdmin in django for a model. ie i have imported the stockprices from nse in excel and imported data from excel in quotations class. the data in the excel gets autoupdated every 2 min, Now my problem is... How should I enable the autoupdate of the prices in the quotations objects whenever the prices in excel gets updated? -
TypeError 'item' object is not iterable
Я хотел чтобы можно было перейти через категории к предметам а через них к их описанию. Но получил такую ошибку. Вот код. views.py from django.shortcuts import render from shop.models import Category, Item, Comment from django.http import HttpResponseRedirect, Http404, HttpResponse def mainpage(request): categorys = Category.objects.all().order_by('name') return render(request, 'shop/mainpage.html', {'categs':categorys}) def items(request, categ_id): try: itemss = Item.objects.get(id = categ_id) except: raise Http404("Not found") return render(request, 'shop/items.html', {'itemss':itemss}) def info(request, item_id): try: item = Item.objects.get(id = item_id) except: raise Http404("No one item is no found") return render(request, 'shop/info.html', {"item":item}) models.py from django.db import models class Category(models.Model): name = models.CharField(max_length = 20, unique = True) def __str__(self): return self.name class Meta: verbose_name = "Категория" verbose_name_plural = "Категории" class Item(models.Model): category = models.ForeignKey(Category, on_delete = models.CASCADE) name = models.CharField(max_length = 20, default = "Unknown") item_desc = models.TextField(default = "Empty") publish_date = models.DateTimeField(auto_now = True) price = models.CharField(max_length = 20, default = 0) quanty = models.CharField(max_length = 10000, default = 0) def __str__(self): return self.name + " " class Meta: verbose_name = "Предмет" verbose_name_plural = "Предметы" class Comment(models.Model): item = models.ForeignKey(Item, on_delete = models.CASCADE) author_name = models.CharField(max_length = 20, unique = True) comment_text = models.TextField(default = "Empty") publish_date = models.DateTimeField(auto_now = True) def __str__(self): return self.author_name … -
Django rest framework error AssertionError `child` is a required argument
when developing my application I ran into a problem AssertionError at /api/update/ `child` is a required argument. Request Method: GET Request URL: http://45.56.80.77/api/update/?token=1234567&ifloorplan=2 Django Version: 3.0.6 Exception Type: AssertionError Exception Value: `child` is a required argument. Exception Location: /root/Env/ifloorplan/lib/python3.8/site-packages/rest_framework/serializers.py in __init__, line 591 Python Executable: /usr/local/bin/uwsgi Python Version: 3.8.2 Python Path: ['.', '', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/root/Env/ifloorplan/lib/python3.8/site-packages'] Server time: Mon, 1 Jun 2020 07:18:31 +0000 that is, I tried to update and create in the database a record of this kind [ { "id": 2, "level": [ { "id": 2, "plan_level": { "img": null, "img_height": null, "img_width": null, "position_x": null, "position_y": null, "level": null }, "images": [ { "id": 2, "cam": [ { "id": 2, "ken_burns": { "effect": null, "start_pos_x": null, "start_pos_y": null, "finish_pos_x": null, "finish_pos_y": null, "start_width": null, "start_height": null, "finish_width": null, "finish_height": null, "cam": null }, "rotation": 0.34, "pos_x": 21.0, "pos_y": 234.0, "width": 1234.0, "height": 234.0, "img": 2 }, { "id": 3, "ken_burns": { "effect": null, "start_pos_x": null, "start_pos_y": null, "finish_pos_x": null, "finish_pos_y": null, "start_width": null, "start_height": null, "finish_width": null, "finish_height": null, "cam": null }, "rotation": 4.0, "pos_x": 354.0, "pos_y": 345.0, "width": 345.0, "height": 345.0, "img": 2 } ], "img": "/media/ifloorplans_source/test.jpg", "level": 2 } ], "tabLabel": "1 st", … -
How to get the sum of a specific column from database in django?
I have written code like this but it is not working Error Displaying : No function matches the given name and argument types. You might need to add explicit type casts. from django.db.models import Sum Coach.objects.aggregate(Sum('number')) -
Pass additional paramenters to django url
I want to pass additional arguments to django url. I am trying to do something when I am passing 'test_data' as an additional argument from testfile but how to send it through url. Urls.py: path('business/average/difference/<str:start_date>/<str:end_date>/', views_noquery.AverageChangeDifference.as_view()), views.py: def mock_funcname(func): def wrapper(request, *args, **kwargs): if kwargs.get("test", None) is not None: print('ghj') return Response({'detail': "Some stuff mocked for this user :)"}) return func(request, *args, **kwargs) return wrapper class AverageChangeDifference(APIView): '''Average change difference''' #permission_classes = [IsAuthenticated] @mock_funcname def get(self, request,*args, **kwargs): print(kwargs) if kwargs.get("start_date", None) is not None and kwargs.get("end_date", None) is not None: dataset = requests.get(config['url']['API_FETCH_URL']).json() change_difference = [] for data in dataset: data_date = datetime.datetime.strptime(data['Date'], "%d-%b-%Y").strftime("%Y-%m-%d") if data_date > kwargs["start_date"] and data_date < kwargs["end_date"] and data['Open']>data['Close'] : change_difference += [data['High']- data['Low']] #sum(change_difference)/len(change_difference) return Response({"Average change difference" : sum(change_difference)}) testfile for restapi: def AverageChangeDifference(self) : response_AverageChangeDifference = client.get('/business/average/difference/'+ self.Start_Date+'/' + self.End_Date +'/',{'test':'test_data'}) self.assertEqual(response_AverageChangeDifference.status_code, status.HTTP_200_OK) return "AverageChangeDifference passed" -
How To Unit Test Blank DateTimeField
I am trying to unit test a form which includes a date selector. It is saved in the model as DateTimeField and in the form uses a DatePickerInput widget. This is the test: def test_form_validation_for_blank_items(self): user = User.objects.create_superuser('username') self.client.force_login(user) form = PersonalInformationForm(data={ 'first_name': '', 'surname': '', 'gender': '', 'dob': ''}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, { 'first_name': ['This field is required.'], 'surname': ['This field is required.'], 'gender': ['This field is required.'], }) And the error that's thrown: AttributeError: 'NoneType' object has no attribute 'year' My other fields are fine, but I was wondering how to unit test a blank DateTimeField model with a DatePickerInput widget. Thank you.