Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can not add values from forms to Django models
I made a form and there I had a multiple-choice field called artists which I got from my database and while adding a song a user can select multiple artists and save the song. The artists are a ManyToManyField in Django models. models.py class Artists(models.Model): """ Fields for storing Artists Data """ artist_name = models.CharField(max_length = 50, blank = False) dob = models.DateField() bio = models.TextField(max_length = 150) def __str__(self): return self.artist_name class Songs(models.Model): """ Fields for storing song data """ song_name = models.CharField(max_length = 30, blank = False) genre = models.CharField(max_length = 30, blank = False) artist = models.ManyToManyField(Artists) release_date = models.DateField() forms.py class Song_input(forms.Form): queryset = Artists.objects.only('artist_name') OPTIONS = [] for i in queryset: s = [] s = [i, i] OPTIONS.append(s) artist_name = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=OPTIONS) song_name = forms.CharField() genre = forms.CharField() release_date = forms.DateField(widget=DateInput) Now I want to get all the values selected from the form and save to my database. Here the artist_name may have multiple values. I have tried using the add() and create() methods but can not figure out how to add all the data where one field (artist_name) having multiple data to my database. -
DRF permission issue even after sending a valid token for a get request
serializer.py class UserDetailSerializer(serializers.ModelSerializer): """for all getting all objects of a particular user """ tags = TagListSerializerField() author=serializers.StringRelatedField(read_only=True) class Meta: model = Post fields = ('id','title','rate','author','content','review','url','tags') views.py class PostListUser(generics.ListAPIView, APIView): serializer_class = UserDetailSerializer permission_classes = [IsAuthenticated] authentication_classes =(TokenAuthentication,JSONWebTokenAuthentication) def get_queryset(self): return Post.objects.filter(author=self.request.user) urls.py url('^me/$', PostListUser.as_view()), but when i tried to hit a get request with all the Authorization headers I have got this response { "detail": "You do not have permission to perform this action." } -
Django form isn't showing the correct fields
The django form to let users change their information fields should let them change username, email, name and last_name, but instead, it shows their nationality, gender, score on app and birthday. views.py def profileedit_view(request): if request.method== 'POST': form= PerfilEditadoForm(request.POST, instance = request.user) if form.is_valid(): form.save() return redirect('login') else: form= PerfilEditadoForm(instance=request.user) args= {'form': form} return render(request, 'profileedit', args) form = UsuarioForm(request.POST or None) if form.is_valid(): form.save() context = { 'form': form } return render(request, "profileedit.html", context) forms.py class PerfilEditadoForm(UserChangeForm): class Meta: model = User fields= ('email', 'username', 'first_name', 'last_name') profileedit.py <form method="POST" action="#"> {% csrf_token %} <p> {{ form.as_ul }} <button class="btn btn-primary py-1 px-2" type="submit" > Save </button> </p> </form> -
mysqlclient install error in python 3.7.4 windows
I created Django project and want to connect with mysql. So, I should install mysqlclient on my win10 system. my command : pip install mysqlclient then I got this error ERROR: Command errored out with exit status 1: command: 'c:\users\2020\appdata\local\programs\python\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\2020\\AppData\\Local\\Temp\\pip-install-o06onpbq\\MySQL-python\\setup.py'"'"'; __file__='"'"'C:\\Users\\2020\\AppData\\Local\\Temp\\pip-install-o06onpbq\\MySQL-python\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\2020\AppData\Local\Temp\pip-record-sdzwwsuw\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\2020\appdata\local\programs\python\python37-32\Include\MySQL-python' cwd: C:\Users\2020\AppData\Local\Temp\pip-install-o06onpbq\MySQL-python\ Complete output (29 lines): running install running build running build_py creating build creating build\lib.win32-3.7 copying _mysql_exceptions.py -> build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building '_mysql' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -Ic:\users\2020\appdata\local\programs\python\python37-32\include -Ic:\users\2020\appdata\local\programs\python\python37-32\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt" /Tc_mysql.c /Fobuild\temp.win32-3.7\Release\_mysql.obj /Zl _mysql.c _mysql.c(42): fatal … -
Why do django render a view with "\n" ? (js parse error)
I'm trying to render a view in Django and send it with ajax to a client. My view.py : def searchUser(request): form = Search(request.POST['name']) found_profiles = User.objects.prefetch_related('profile').filter(artist_name__icontains=request.POST['name'])[:20] profiles = {} i = 0 for user in found_profiles: profile = Profile(user = user) profiles.update({i : {'user' : user,'profile' : profile}}) i+=1 print('profile '+str(profiles)) return render(request, 'home_page/search_results.html', {'profiles' : profiles}) My search_result.html : {% for tuple, cont in profiles.items %} <h2>{{cont.user.email}}</h2> <h2>{{cont.user.artist_name}}</h2> <h2>{{cont.profile.bio}}</h2> {% endfor %} And finally my js : <script type="text/javascript"> $('#submit-search-user').on('click', function(){ var name = $('#id_Name').val(); console.log("Seaching for "+name); $.ajax({ type: "POST", url: "/ajax/search/user", data: {name: name, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType : 'json', error : function(xhr, errmsg){ console.log(xhr); console.log(errmsg); }, success : function(data) { console.log(data) $('#result').html(data); } }); }); </script> Js output a parse error, the "responseText" part is : "\n\n\t<h2>test@outlook.fr</h2>\n\t<h2>Azerrt</h2>\n\t<h2></h2>\n\n\t<h2>moowee@yo.de</h2>\n\t<h2>a</h2>\n\t<h2></h2>\n\n" Why is there any "\n" and "\t" ? Is this the reason of my parse error ? -
i want equivalent django query for follwing Sql query,
SELECT roomid FROM hotel WHERE book_date >= startdate AND book_date < enddate GROUP BY roomid HAVING sum(booked=1)=0 or if there is any way to convert raw queries output to Django queryset for eg. 1. objectQuerySet = Article.objects.filter(booked=1) print(type(objectQuerySet)) >> <class 'django.db.models.query.QuerySet'> 2. with connection.cursor() as cursor: query = "select * FROM api_basic_article WHERE booked = 1" cursor.execute(query) queryset = cursor.fetchall() print(type(queryset)) >><class 'list'> can I convert list object to django.db.models.query.QuerySet? my final aim is to response a json serialized file for the rest api request at django -
What is the best way to create django app for language learning
I currently want to create an app built on Django. I had some experience with this framework a year ago but I gave up eventually. And now I want to go back to development. And so I decided to create an app for learning 500 most used words in the English language. I've basically made everything look nice and smooth, but I got stuck in the back-end part. And I seek advice, how to create an interactive app for the flashcard web app. What libraries are used in the most advanced Django apps(I'm okay with reading a lot of material), how to authorize with google accounts, how to collect data from users and know the statistics of the app. I've read the documentation, watched a lot of tutorials, but they basically teach the low skill stuff and nothing else. My question is if you were to create an advanced Django app for memorizing 500 frequently used words in the English language, what would you use?. How would you do it?. In what order? -
Which one of LF and CRLF should I use in a django project?
I am collaborating on a course-django project with other several students, and I found line separator mixed up, some files use LF, and other files use CRLF. I feel confused, although now everything is well, no one knows future. so which one we should set in project level? do you have any suggestions? -
html page is loaded from disk cache but event.persisted is false
I have this to my javascript file: window.addEventListener('pageshow', function(event) { if (event.persisted) { console.log('Page was loaded from cache.'); } }); but if i navigate to another link and then hit back button, my html page is loaded from disk cache and the event.persisted is false. Any suggestions? -
How to increase timeout while uploading on the Sanic framework?
I have a method in Sanic for uploading files. Sometimes my file size is large or the connection between server and clients is poor So, in this situation I lose my request because the clients occur with a timeout exception. I want to increase timeout on top of a specific method. # I want to define set timeout period here # @set_imeout(4 * 60) @song.route('/upload', methods=["POST"]) @is_authenticated() @required_roles(['cafe']) @jsonify async def process_upload(request): # upload method do something for upload -
How to protect page by password
I have a project where users can join rooms, but i want to protect room with password.How to implement that? Maybe some decorators or something like that -
create django model with field names from list
I have a django model in my models.py file like this: class Inventory(models.Model): player = models.CharField(max_length=30) apples = models.IntegerField() bananas = models.IntegerField() Where each "player" has different numbers of fruits in his inventory. I will change the possible fruits over time, thus I would like to create these fields dynamically from a list. So right now the list would be ["apples", "bananas"] but at a later point in time I would like to have ["apples", "oranges", "lemons"]. Is there a way to create the field names from a list? -
TravicCI build dont find Managa.py [Django] command
im following a tutorial and a complete newbie. in the tutorial the tutor used docker as virtual envioremnt and because im currently using my Win-10-Home machine i've decided to use plain 'ol python venv. for some reason TravicCI is not fiding my manage.py command, and i cant figure out why! this is the TCI log 0.58s$ git clone --depth=50 --branch=master https://github.com/therealgenish/recipe-app-api.git therealgenish/recipe-app-api $ source ~/virtualenv/python3.6/bin/activate $ python --version Python 3.6.7 $ pip --version pip 19.0.3 from /home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pip (python 3.6) install $ pip install -r requirments.txt $ app\manage.py test && flake8 appmanage.py: command not found The command "app\manage.py test && flake8" exited with 127. Done. Your build exited with 1. the reason it's app\manage.py and not manage.py is because it's outside the app folder, so i figured.. the .travis.yaml : language: python python: - 3.6 install: - pip install -r requirments.txt script: - app\manage.py test && flake8 and a link to the github project -
How to differentiate between modules with same name in Django
For example, there is a 'reverse' module in Django which you can use for easy navigation between links. There is also a 'reverse' module available in DRF which can be used for creating custom API endpoints easily. I'm sure people at some point need to use both the modules at different stages, but how is Django going to differentiate between these two modules? They are called almost in the same way. Or am I wrong? Maybe either of the modules can be use to carry out both the tasks? -
Dependent Nested Category in Django
I want to create 2 category 1 Main category ex a. MEN b. Woman and 2 Subcategory would be according to parent category. How I can perform these actions. class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey( Category, null=True, blank=True, related_name='children', on_delete=models.CASCADE ) def __str__(self): return self.name def save(self, *args, **kwargs): # prevent a category to be itself parent if self.id and self.parent and self.id == self.parent.id: self.parent = None super().save(*args, **kwargs) class Product(models.Model): categories = models.ForeignKey( Category, related_name='products', blank=True, on_delete=models.CASCADE ) categorychild = models.ForeignKey(SubCategory, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=255) How I can solve this Im putting this question 3rd time Please help -
Separate media settings for each app in django
I am working on building a django based blog-like site, it currently has one app. It contains a media folder which contains the images uploaded by the user. However, the MEDIA_URL and MEDIA_ROOT are specified in the main settings.py file. But in the future, there will be more apps containing more media, thus I want separate MEDIA_URL(s) and settings for each app. I tried writing the MEDIA_ROOT and MEDIA_URL separately in the apps.py file, but removing this from the main settings.py file results in an error. I also tried using FileSystemStorage, but even this needed me to have a MEDIA_URLS in the settings.py file. Please let me know if you need any more details. Any help is appreciated, thanks. -
Django Email - [Errno 2] No such file or directory
I am looking to allow the user to upload and send a document via email from my django app. When I go to send the email I get the error "[Errno 2] No such file or directory:". I have tried using a relative path as well as specifying the path but I get the same error either way. I can see that the file is being successfully loaded to that location...so I feel I must be missing something obvious here. Here is my view: def email(request): if request.method == "POST": form = EmailForm(request.POST,request.FILES) if form.is_valid(): post = form.save(commit=False) # post.published_date = timezone.now() post.save() email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') document = request.FILES.get('document') email_from = settings.EMAIL_HOST_USER recipient_list = [email] email = EmailMessage(subject,message,email_from,recipient_list) base_dir = 'media' email.attach_file('Desktop/WBU2/Poseidon/media/media/'+str(document)) #also tried email.attach_file('/media/'+str(document)) email.send() else: form = EmailForm() return render(request, 'docemail.html', {'form': form}) models.py class Mails(models.Model): email = models.EmailField() subject = models.CharField(max_length=1000) message = models.CharField(max_length=20000) document = models.FileField(upload_to='media') def __str__(self): return self.email -
cleaned_data for extra fields in django ModelForms
I have the ModelForm below with an extra field named decimal_part: class MyObjectForm(forms.ModelForm): class Meta: model = MyObject exclude = [] def __init__(self, *args, **kwargs): super(MyObjectForm, self).__init__(*args, **kwargs) self.fields['decimal_part'] = forms.IntegerField( required=False, label=mark_safe('<br/>'), widget=forms.NumberInput( attrs={ 'type': 'text', 'data-type': 'number', 'placeholder': ' cm', 'maxlength': '2', })) def clean_decimal_length(self): data = self.cleaned_data['decimal_part'] return data and the template: <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <table> #...some form attr.s ...# {{ form.decimal_part}} </table> <input type="submit" value="Submit"> but after submitting the form correctly I'm getting a KeyError: 'decimal_part' data.get('decimal_part') returns None and decimal_part is not in self.cleaned_data any thoughts? thank you for you help! -
how to do Inner join using django orm
MY models.py class Forms_in_Document(models.Model): document_submit = models.ForeignKey(Document_submit, on_delete=models.CASCADE) class Document_data(models.Model): forms_in_document = models.ForeignKey(Forms_in_Document, on_delete=models.CASCADE) document_structure = models.ForeignKey(DocumentStructure , on_delete=models.CASCADE) date_created= models.DateTimeField(default=datetime.now(),null=False) string = models.CharField(null=True, max_length=100) integer = models.IntegerField(null=True) date_time = models.DateTimeField(null=True) class Application(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, null=False) date_created = models.DateTimeField(default=datetime.now(),null=False) forms_in_document = models.ForeignKey(Forms_in_Document, on_delete=models.CASCADE, null=True) closed = models.BooleanField(default=False, null=False) new = models.BooleanField(null=False) media = models.BooleanField(default=True) Path_info = models.ForeignKey(Path_info, on_delete=models.SET_NULL,null=True) The raw sql query that i am trying to do in django is "Select * from Application app inner join Document_data dd on dd.forms_in_document=app.forms_in_document where [some filter]" How can i do this using django Thanks in Advance -
Shared authentication between Laravel and Django apps coexisting in the same domain
I have a Laravel app which contains authentication code(and a lot more including Sass subscriptions and payment gateway integration), and a Django app which contains the main routes of the application. Both of them coexist in the same domain, let's say the Laravel app resides in the /auth url and the django project resides in the / url. I want to share the authentication between the two applications, (ie) if the user logs in using a Laravel form and is redirected to the Django route, he must stay authenticated. Any suggestions and links to relevant sources will be appreciated. Forgive me if the question seems too basic. Either of the applications can't be rewritten in another , since the Laravel app has too many functionalities to be rewritten and the Django part contains some machine learning functionality -
Probrems with URLconfs in Django
I include authentication URLconf in my urls.py: path('accounts/', include('django.contrib.auth.urls')), And it urlpatterns contains this: path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), path('password_change/', views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password_reset/', views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), But when I go to 127.0.0.1:8000/accounts debuger shows me this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts Using the URLconf defined in locallibrary.urls, Django tried these URL patterns, in this order: 1. admin/ 2. catalog/ 3. ^static\/(?P<path>.*)$ The current path, accounts, didn't match any of these. Why doesn't django see my URLconf? -
How to include authentication in a group of everyone in django?
How to include authentication in a group of everyone in django? for example. Main group router / (how to add group authentication here?) -- /route1 Route 1 -- /route2 Route 2 Is it easy to understand? Thank you. -
Django - Sorting posts by categories
I have two models -BlogPost and PostTopic. I would like to be able to filter by topic and see all the posts for that topic. This is working when I load up each url directly (i.e blog/cat/1), however when linking to this from the main blog post list view, I have tried the below template code: {% for topic in object_list %} <li><a href="{% url 'blog:BlogPostTopic_list' pk=topic.pk %}">{{ topic.topic }}</a></li> {% endfor %} However this doesn't work as it iterates over each topic mapped to the post (resulting in duplicates), rather than each unique topic. How do I link just to the unique topic page? models.py class PostTopic(models.Model): top_name = models.CharField(max_length=264, unique=True) def __str__(self): return self.top_name class BlogPost(models.Model): title = models.CharField(max_length=200) snippet = models.CharField(max_length=400, null=True) blog_pic = models.ImageField(upload_to='blog_pics', default='placeholder.jpg') hero_pic = models.ImageField(upload_to='blog_pics',blank=True) content = models.TextField() topic = models.ForeignKey(PostTopic, on_delete=models.CASCADE) create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def get_absolute_url(self): return reverse("BlogPost_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title views.py class BlogPostListView(ListView): model = BlogPost paginate_by = 4 def get_queryset(self): return BlogPost.objects.all().order_by('-published_date') class BlogPostDetailView(DetailView): model = BlogPost class BlogPostTopicListView(ListView): model = BlogPost template_name = 'blog/post_category.html' def get_queryset(self): return BlogPost.objects.filter(topic=self.kwargs['pk'] ) url url(r'^$',views.BlogPostListView.as_view(),name='BlogPost_list'), url(r'^(?P<pk>\d+)$',views.BlogPostDetailView.as_view(),name='BlogPost_detail'), url(r'^cat/(?P<pk>\d+)$',views.BlogPostTopicListView.as_view(), name='BlogPostTopic_list'), -
Who to display image in Django
I'm very new to Django so I saved an image into the database inside my models.py class Article(models.Model): title = models.CharField(max_length=120) content = models.TextField() active = models.BooleanField(default=True) picture = models.ImageField(upload_to='documents/pictures', null=True) now I want to display this image and I used the get_absolute_url method to get the current data from a row inside the db: def get_absolute_url(self): return f'/blog/{self.id}' In the views.py I return a renderfun with the params 'article':get_object_or_404(Article, id=my_id). Now in my template index.html I have this {% block content %} {{ article.content }} <img src="{{ article.picture }}" style="width: 200px; height: 200px;" /> {% endblock %} But if I open the developer console in chrome the img path is the same I set in models.py. The document/pictures folder is at the root of the django app. I tried to move it into the current app (Blog) but this also doesnt work. Do I have to set the media path in the settings.py ? I use django 3 and sqlite3 as db -
customize registration form in django
I created a registration form in django with blow codes forms.py: class UserFormRegistration(UserCreationForm): username = forms.CharField(label = 'نام کاربری') email = forms.EmailField(required=True, label = 'ایمیل') password1 = forms.CharField(label= 'رمزعبور', widget = forms.PasswordInput, strip = False) password2 = forms.CharField(label= 'تکرار رمز عبور', widget = forms.PasswordInput, strip = False) class Meta: model = User fields = ["username", "email", "password1", "password2"] views.py: def register(request): if request.method == "POST": form = UserFormRegistration(request.POST) if form.is_valid(): user =form.save() username = form.cleaned_data.get("username") login(request, user) messages.success(request, f"تبریک! اکانت شما با نام {username} با موفقیت ساخته شد") return redirect ("/") else: form = UserFormRegistration() return render(request, "accounts/registration.html", {"form":form}) So now, when i try to register with this form in the website i get some error like: The two password fields didn’t match. Enter a valid email address. The password is too similar to the username. How can i change these errors? For example i want to change the language and i don't want third error at all