Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create model instance out of Form and add it to other instance
In my models.py I have model called Bus. It contains multiple fields, including the field file below: class Bus(models.Model): file = models.OneToOneField('File', on_delete=models.PROTECT, editable=False) The File model consists of: class File(models.Model): file = models.FileField( upload_to=get_filepath, max_length=45, validators=[ FileExtensionValidator(allowed_extensions=['pdf', 'jpg', 'png']), file_size, ] ) original_name = models.CharField(max_length=45) extension = models.CharField(max_length=3) When you want to create a new Bus I need of course a form. That's defined in my forms.py: class BusForm(forms.ModelForm): upload = forms.FileField(max_length=45, required=False, validators=[ FileExtensionValidator(allowed_extensions=['pdf', 'jpg', 'png']), file_size, ],) My problem: In the save() method of BusForm I have to create a File instance and add it to the Bus instance (file field). For multiple hours I tried to achieve that. However, I don't get it. If someone could try to help me how the save() method has to look like, that would be great! -
Django autosetting user foriegnkey field to submitting user on form
What I'm trying to do is to auto set a field of a model to the user that is submitting the form. Models.py: class startcampaign(models.Model): title = models.CharField(max_length=30) description = models.TextField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Forms.py: class StartCampaignsForm(forms.ModelForm): class Meta: model = startcampaign exclude =['user'] Views.py: def register(request): if request.method == 'POST': form = StartCampaignsForm(request.POST) if form.is_valid(): campaign_register = StartCampaignsForm.save(commit=False) campaign_register.user = self.objects.get(user=self.user) campaign_register.save(commit=True) return redirect('home') else: form = StartCampaignsForm() return render(request, 'Campaigns/register.html', {'form': form}) When I run this currently, I get save() is missing a positional argument 'self'. I' not dedicated to this method. I just need a working example that lets me autoset the user which is submitting the form to the foreign key field of 'user' in my model. -
Comparing DateField in Django, workd in 1.8.8 but throws error in 1.11.11
In the model... Event.date = models.DateField(default=datetime.date.today) In the view... import datetime future_events = Event.objects.filter(date__gte=datetime.date.today).order_by('date', 'start_time') The Error? expected string or buffer Request Method: GET Request URL: http://127.0.0.1:8000/event/ Django Version: 1.11.11 Exception Type: TypeError Exception Value: expected string or buffer Dont understand whats not working here worked okay before I upgraded Django but fails now. Any help is appreciated. -
Accessing list of dictionaries in template by index
I have a list of dictionaries in the django template. I wish to use its values in a form. [ { "movie_id": 1950, "title": "In the Heat of the Night (1967)" }, { "movie_id": 3741, "title": "Badlands (1973)" }, { "movie_id": 3959, "title": "Time Machine, The (1960)" }, { "movie_id": 4101, "title": "Dogs in Space (1987)" }, { "movie_id": 8572, "title": "Littlest Rebel, The (1935)" }, { "movie_id": 65230, "title": "Marley & Me (2008)" }, { "movie_id": 105954, "title": "All Is Lost (2013)" } ] In my template, I want to get values of each field by index. ie. for the list[0]['movieId'], I would like to get the value 1950. Is that possible? -
How to use external data in Django?
I have an existing Python module which encapsulate my Business Logic and itself is connected to a backend-database. import project-backend stations = project-backend.getStations() #returns a dict() stations['zurich'].getPipes() # etc. etc. As a Django-Newbie, how can I use this existing BL-module in a Django app? My Webapp does not need to store anything, because everything is handled by the existing BL. Do I need to import the existing BL-module within the representing model's definition an disable the managing (managed=False)? Or shall I implement a custom-manager which routes all queries to the BL-module? -
running django project in visual studio 2013 python exe opens but not running
I have installed VisualStudio2017 with python option enabled. I am trying to migrate my existing Django project (python 2.7) to python 3.6 . The solution build successfully in visual studio 2017 but when i am running the application (F5) , python exe opens but not executing & shows black screen and also Visual studio closes automatically. I have same issue in enter image description herevisual studio 2013 (python 2.7) , That's why i am trying to migrate to Visual Studio 2017. But the issue i had faced not solved. -
Django: save() got an unexpected keyword argument 'commit'
In my forms.py I have a custom ModelForm that contains a save() method: def save(self): bus = super().save(commit=False) datei = self.upload.name original_dateiname = datei.name extension = original_dateiname.split('.')[-1] a = Datei.objects.create(file=datei, original_dateiname=original_dateiname, extension=extension) self.datei = a bus.save() return bus However, now I get the error: save() got an unexpected keyword argument 'commit' What's wrong here? -
How to exclude some query from inline Django admin model?
Django 2.0.3, Python 3.6.1. I try to filter QuerySet of one field (ForeignKey) on inline model (Django Admin). # ./app/models.py class Product(models.Model): product_id = models.PositiveSmallIntegerField() class Price(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.PositiveSmallIntegerField() # ./app/admin.py class PriceInlineAdmin(admin.TabularInline): model = Price @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ('id',) inlines = [ PriceInlineAdmin ] How to exclude from PriceInlineAdmin QuerySet products with ID start with 1? -
Django paypal ngrok
It is so strange. I integrated paypal on my django project few months before. It worked, but currently it doesn't. But I haven't changed anything. I tested an old version and it is the same. I think do what I have to do: -firstly I run my server -secondly I run ngrok python3.6 mange.py runserver 8080 ./ngrok http 8080 My payment is accepted by Paypal, I have a notification too, but I don't receive any signal and any model is created. Nothing indicates an error. It's look like if I don't use ngrok, but I do ! I do everything whith ngrok url. I have : PAYPAL_RECEIVER_EMAIL="myemail-facilitator@gmail.com" PAYPAL_TEST = True valid_ipn_received.connect(myfonction) paypal_dict = { "business": "myemail-facilitator@gmail.com",# "amount": price, "item_name":"Achat XXX", "invoice": id, "currency_code": "EUR", "custom":request.user.id, "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return_url": request.build_absolute_uri(reverse('payment:done', kwargs={'id': id})), "cancel_return": request.build_absolute_uri(reverse('payment:canceled',kwargs={'id': id})), } I use myemail-buyer@gmail.com to buy. I think that I don't do just a little thing but what ? If somebody can help me... I become crazy Thank you ! ̀ -
Django Responsive Form using class:'form-control'
I have a from and added class':'form-control' to every field of the form to make them responsive like this : companyname=forms.CharField( widget=forms.PasswordInput(attrs={'class':'form-control' ,'style': 'width:30%'}) ) but when i add form-control class , the label is showd at the upper row of the text box i dont know what to do to bring the label beside the text box when it has no class the code below is ok but its not responsive <div class="panel-body" style="text-align:right ; margin-left:auto;margin-right:auto;width:80%;"> <div style="width:85% ;margin-left:auto;margin-right:auto;"> <form enctype="multipart/form-data" method="post" > {% csrf_token %} {{ profile_form.as_p}} <input id="savepersonalinfo" type="submit" name="" value="ثبت"> </form> </div> </div> and also how can i put the textboxes arranged exactly in same column ? in the picutre iust companyname has form-control class and is responsive and other fields are not -
GIT: Moving all content of a parent/subfolder to parent/
I am new to Github. I have uploaded my Django app to Github that I will be using on Heroku. I successfully added files and folders on the web interface of Github but realized that I incorrectly uploaded folders. I cloned my github repo on my local machine. I have a sub-folder that I want to move to it's parent folder but the git mv is not working for me or I am doing something wrong I can't figure out what. parent folder: PH_Dorms sub folder: ph_dorms 1st try: cd PH_Dorms git mv ph_dorms ../ Result: fatal: '../' is outside repository 2nd try: cd PH_Dorms git mv ph_dorms ./ Result: "fatal: can not move directory into itself, source=ph_dorms, destination=ph_dorms 3rd try: cd PH_Dorms cd ph_dorms git mv ph_dorms ./ Result: fatal: can not move directory into itself, source=ph_dorms/ph_dorms, destination=ph_dorms/ph_dorms 4th try: cd PH_Dorms cd ph_dorms git mv ph_dorms ../ Result: fatal: cannot move directory over file, source=ph_dorms/ph_dorms, destination=ph_dorms 5th try: cd PH_Dorms cd ph_dorms git mv ph_dorms/* ../ Result: fatal: bad source, source=ph_dorms/ph_dorms/, destination= 6th try: cd PH_Dorms cd ph_dorms git mv * ../ Result: fatal: bad source, source=ph_dorms/, destination= 7th try: cd PH_Dorms cd ph_dorms git mv * ./ … -
django mongoengine unable to login using correct password
I am using mongoengine with django rest framework and default User model settings.py has : AUTHENTICATION_BACKENDS = ( 'mongoengine.django.auth.MongoEngineBackend', ) SESSION_ENGINE = 'mongoengine.django.sessions' SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer' MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User' AUTH_USER_MODEL = 'mongo_auth.MongoUser' views.py has : from django.contrib.auth import login, logout from mongoengine.django.auth import User @csrf_exempt def log_in(request): js = json.loads(request.body) try: #user = User.objects.get(username=request.POST['username']) user = User.objects.get(username=js['username']) print user.username print user.password print js['username'] print js['password'] print user.password==js['password'] #if user.check_password(request.POST['password']): if user.check_password(js['password']): user.backend = 'mongoengine.django.auth.MongoEngineBackend' user = authenticate(username=js['username'], password=js['password']) login(request, user) request.session.set_expiry(60 * 60 * 1) # 1 hour timeout return HttpResponse(user) else: return HttpResponse('login failed') except DoesNotExist: return HttpResponse('user does not exist') except Exception: return HttpResponse('unknown error') with the correct password, I am getting login failed. What can be the reason for this? -
Issue styling the image upload button
Basically I am trying to style my image upload form field. By following guidance from another question from here I ended up doing this: document.getElementById("uploadBtn").onchange = function () { document.getElementById("uploadFile").value = this.value; }; .fileUpload { position: relative; overflow: hidden; margin: 10px; } .fileUpload input.upload { position: absolute; top: 0; right: 0; margin: 0; padding: 0; font-size: 20px; cursor: pointer; opacity: 0; filter: alpha(opacity=0); } <input id="uploadFile" placeholder="Choose File" disabled="disabled"/> <div class="fileUpload btn btn-primary"> <span>Upload</span> <input id="uploadBtn" type="file" class="upload"/> </div> This works as it should but how do I bind it to my django form field ? If I replace class attribute inside the input from "upload" to "profile_pic", the main upload button will appear, which is bad. Or am I doing it wrong ? I just need the information to be passed to my form. photo = forms.ImageField(required=True, widget=forms.FileInput(attrs={'class': 'profile_pic'})) -
How to handle django dabase migrations with captain duck duck?
machine: docker 1GB when i try manage.py migrations (after a successful makemigrations) in my already deployed captain-definition, i get this error, Probably because migrations are not synced in my git repo and django cant detect which migrations are already applied to the database without the migrations folder Captain duck duck seems to destroy any changes to the file system in my docker conatiner and hence the migrations folder is not available after a restart. System check identified some issues: WARNINGS: Users.CustomUser: (auth.W004) 'CustomUser.phone_number' is named as the 'USERNAME_FIELD', but it is not unique. HINT: Ensure that your authentication backend(s) can handle non-unique usernames. Operations to perform: Apply all migrations: Exams, Users, account, admin, auth, contenttypes, sessions, sites, socialaccount Running migrations: Applying Exams.0002_auto_20180309_1911...Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column "owner_id" of relation "Exams_topic" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", … -
Passing a url variable after submitting a form
I'm working on a simple website where I can register isolated information systems in a simple database, and assign harddisks to each system using ForeignKeys. When deleting a system from the database, I use a DeleteView. In the DeleteView: To check if there are any harddisks associated with the system I use custom method. If no harddisks are found, it displays the DeleteView form. If there are any, a list of the relevant harddisks is displayed instead of the form, with a link to the UpdateView of each individual harddisk. I want to be able to click a link to one of these harddisk, make changes to it in the UpdateView, then be redirected back to the DeleteView to "check the list again". This is what I have so far (Media = harddisk/storage media) class MediaEdit(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = Media form_class = MediaForm template_name = 'dsl/media/media_create-edit.html' success_message = 'Media successfully changed!' def get_success_url(self): return reverse('dsl:media_edit', kwargs={'pk': self.get_object().id}) def get_context_data(self, **kwargs): context = super(MediaEdit, self).get_context_data(**kwargs) context['action'] = reverse('dsl:media_edit', kwargs={'pk': self.get_object().id}) next_url = self.request.GET.get('next', 'None') context['next_url'] = next_url return context I have tried using the "next_url" variable in my UpdateView form: {% if next_url %} <form class="" action="{{ next_url }}" method="post"> … -
Syntax error in "manage.py" file - django 2
I do not understand what the problem is but I keep getting a syntax error for the "from exc" line even though I did not alter the code. I have checked for un-closed parentheses and quotes and indentation look right to my beginner's eye. The issue is that this is the out-of-the-box code for the Django 2.0 virtual environment so I can only assume Sublime somehow formatted it wrong when the file was dragged into the text editor? import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) -
in my project how can i set http session tracking login time for 30 second only
In my project i want to set HTTP Session tracking for 30 second after 30 second user should be logout automatically, if user is not doing any think and also one more condition after login if user click on back button of my browser and than forward button of my browser than it must be transfer on login page for entering username and password. In my project i want to set HTTP Session tracking for 30 second after 30 second user should be logout automatically, if user is not doing any think and also one more condition after login if user click on back button of my browser and than forward button of my browser than it must be transfer on login page for entering username and password. In my project i want to set HTTP Session tracking for 30 second after 30 second user should be logout automatically, if user is not doing any think and also one more condition after login if user click on back button of my browser and than forward button of my browser than it must be transfer on login page for entering username and password. Views.py from django.shortcuts import render from django.http import … -
I need an explanation on how Django mobile apps work
So I want to create a mobile app with Django, that is basically like a sort of online store, I'm still very confused on how the process would work, but this is what I understand so far : The backend would be built with Django, which would manage users and data and all that, and then I would use MySQL to store the products and their relevant information, and Django would access that database and display the products as programmed. But then comes the matter of the interface of the app. I know that Django can display HTML pages so could those html pages act as the interface to the app, and how would I be able to achieve that on a mobile platform ? I know these kind of questions are not suitable for the stack overflow format but tbh I don't know where else to go so thanks. -
Can you help me find the error for querry in django?
So I am trying to make a search function which looks through the database to look for similar words in django database. My views.py: def result(request): # Shows the matched result request.GET.get('q') incubators = Incubators.objects.all() check = Incubators.objects.filter(incubator_name__icontains="q") return render(request, 'main/results.html', {'incubators':incubators,'check': check}) The problem is that my HTML page is not showing any result matching to the database when I know there is. Its just a black HTML page. {%extends 'main/base.html'%} {%block content%} {%for inc in check%} <p>{{inc.incubator_name}} <br> {{inc.city_location}}</p> <hr> {%endfor%} {%endblock%} I am new to Django and really confused what I am doing wrong here. -
Prevent server from interpreting uploaded files
I have a FileField where the user is meant to upload an image or video for their post: image = models.FileField(null=True, blank=True) Is there any measure I need to take to prevent users from uploading hostile files? Such as .php files? Or does Django's security already prevent that? -
"ailed to create process" when make new virtual environtment python
i using python 3.6.4 and only use it. I have install pip, v i r t u a l e n v, and v i r t u a l e n v w r a p p e r - w i n, but when i make new virtual environment using v i r t u a l e n v d j a n g o - e x a m p i have try use m k v i r t u a l e n v d j a n g o - e x a m p too, but both of it not worked, i have check it with pip freeze the result is good, i have installed all of them, but why i cannot make new virtual environment (i got message "failed to create process")? -
It is possible to check in django rest query filter using .upper()
How to compare value in db with request.data after changing both to upper case str_code = CustomerAccount.objects.filter(strAccountCode.upper() = request.data['strAccountCode'].upper(),chrDocumentStatus='N') -
What is the effective way of managing threads?
I am building a ToDo web-app in Django. This app will create a reminder and will send a text-based SMS to the given phone number. So I decide the given below algorithm: Take user input of Time and Reminder. Validate the input. If valid, store in database and create a thread for sending SMS. Else, display an error message. This algorithm was working well until I came across an article in which it has said that we should not use Threads in web app cause it will use a lot of resources. This is true for my app because I am planning to use my app in such a way that a user can create only 100 reminders. This will create 100 threads on my app per user. I decided to develop a Priority Queue which will insert these 100 threads based on the priority of Time user has provided as input. Now my question is : Does creating a Thread and putting it in a Queue decreases the load on CPU or not? If not, what is the alternative? NOTE : I already know about CELERY and REDIS. But I decided to go this way because I want to … -
Django - Simple User Register not working [Not saving to DB]
I have simple user registration page, but its not saving to the database. Issue: Register form displays, upon clicking submit button, doesn't do anything! Stays there (it should show a HttpResponse('User Registered') And save to db I've know I'm missing something, but what? ideas please. Views.py from django.shortcuts import render from django.views.generic import CreateView from website.forms import RegisterUserForm from django.http import HttpResponseForbidden # Create your views here. class RegisterUserView(CreateView): form_class = RegisterUserForm template_name = "account/register.html" # Overide dispatch func - check if the user is authenticated or return forbidden def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): return HttpResponseForbidden() return super(RegisterUserView, self).dispatch(request, *args, **kwargs) # Overide form valid method behaviour def form_valid(self, form): # False commit - don't save to db, locally cleaning users password first user = form.save(commit=False) user.set_password(form.cleaned_data['password']) user.save(); # Change to redirect - later one! return HttpResponse('User Registered') def Home(request): return render(request, 'account/home.html') Register.html {% extends 'base.html' %} {% block title %} Register {% endblock %} {% block head %} {% load static %} <link href="{% static 'forms.css' %}" rel="stylesheet"> {% endblock %} {% block heading %} <h1>Register</h1> {% endblock %} {% block body %} <div class="bg-contact2" style="background-image: url('images/bg-01.jpg');"> <div class="container-contact2"> <div class="wrap-contact2"> <form class="contact2-form validate-form"> <span class="contact2-form-title"> … -
Download a file using Django rest framework by authenticating the user
I am working on a project where I am using Django as the back end. I am working with Django rest framework, and I have an API to download a File. @detail_route(methods=['GET'], permission_classes=[IsAuthenticated]) def test(self, request, pk=None): try: ticket = Ticket.objects.get(id=pk, user=request.user) file_path = ticket.qrcode_file.path if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="image/jpeg") name = "%s %s %s %s.jpg" % (ticket.show.title, datetime.strftime(ticket.show.date_time, "%H_%M_%p"), datetime.strftime(ticket.show.date_time, "%d %B %Y"), ticket.id) response['Content-Disposition'] = "attachment; filename=%s" % name.replace(" ", "_") return response return Response({'error': 'Ticket doest not belong to requested user.'}, status=status.HTTP_403_FORBIDDEN) except Ticket.DoesNotExist as e: return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND) On the front-end I am using Nuxtjs (ssr for vuejs). This is a little snippet of code, where a user can download the file by clicking a link of target blank.: <a class="downloadBtn" target="_blank" :href="`${baseURL}/payments/api/tickets/${ticket.id}/download_ticket/`">Download e-ticket</a> The web app is running on Nuxtjs server (localhost:3000) and Django server is running on localhost:8000, only the API is used to communicate between the Nuxtjs and Django by using the auth token. When I click the download link it opens up a new tab and make a request from that new tab, where no token is passed with the request. And since, the django …