Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing default paramter value to view method in django is not working
I am very new to Django. I am trying to use an URL with optional parameter, If I pass an URL including the optional Parameter, everything works as expected, but when I try to use an URL without the optional parameter I am getting a 404 page not found error. My urls.py file content from coffeehouse.stores import views as stores_views urlpatterns = [ url(r'^store/(?P<store_id>\d+)/',stores_views.details) ] stores/views.py file content def details(request, store_id='1'): store_info={ 'store_id':store_id } return render(request, 'stores/details.html',store_info) I am unable to figure out why the default parameter is not considered. I am using Django 1.11, I am not sure if there is anything related to the version of Django. -
Django test send post request to next url
I am writing a test case where after login user redirects to the form which is being called by middleware and shown to user. So now user has to submit the form after which on submitting user redirects to normal page. middleware.py def process_view(self, request, view_func, *view_args, **view_kwargs): if condition: ... ... return redirect('%s?next=%s' % (reverse('form'), request.path)) else: return None form.html <form action="{% url 'form'%}" method="post"> <div> <input type="radio" id="yes" name="is_accepted" value="yes" onchange="activateButton(e)" checked> <label for="input1" >Yes</label> <br> <input type="radio" id="no" name="is_accepted" value="no" onchange="activateButton(e)"> <label for="input2">No</label> <input type="hidden" id="next" name="next" value="{{ next }}"> <button type="submit" name="submit" id="submit">Submit</button> </div> </form> As soon as form data is submitted the middleware should exit and return to normal or next page. Its working normal in browser but while test the form is shown but data is not been save on post request. response = client.post(form_url, {'is_accepted': 'yes'}, follow=True) After sending the post request still the response content is the form content. -
Is virtual environment in Django different in different Operating Systems?
I'm a beginner in web programming. I've been working on a Django project along with my teammates. I'm using Mac and he's using Ubuntu. I want to know if the virtual environment created in my system will work on his machine if I sent him mine. Is it differently built on different Operating systems? -
How to write queryset across 3 tables in Django?
I want to write queryset across 3 tables. (models are shown as below) As outcome, I want to get below information. {"naming1":"lpd1","naming2":"lpd2",...} Can anyone tell me how to write this query? models.py class zone(models.Model): zone=models.CharField(max_length=20) def __str__(self): return self.zone class light(models.Model): zone=models.OneToOneField(zone, primary_key=True, on_delete=models.CASCADE) lpd=models.IntegerField() <=extract class naming(models.Model): zone=models.ForeignKey(zone) naming=models.CharField(max_length=20) <=extract -
crispy form - Django SelectDateWidget
Am using crispy forms and SelectDateWidget in django. This is my sample form class SignupForm(ModelForm): class Meta: model=NGO fields=['Organization_Name','Contact_Person','Email_id','Mobile_no','Address','City','Pincode','Website','Established_on'] widgets = { 'Address': forms.Textarea, 'Email_id':forms.EmailInput,'Established_on':forms.SelectDateWidget(years=range(1900,datetime.today().year+1)) } In my html am accessing the Established_on field as {{ form.Established_on | as_crispy_field }} But it displays in vertical View. I tried with {{ form.Established_on_day | as_crispy_field }} But it gives error "as_crispy_field got passed an invalid or inexistent". I want to display Month,Day and Year in a Single Row. -
Creating A Timer For an Academic Quiz
I am creating a web app that's supposed to ask 90 questions in 180 mins. The backend uses Django, while the frontend uses the trio of HTML, CSS and Jquery, Javascript. I've managed to implement the display and entering the questions part. However I'm having issues implenting the timer part. Specifically, I've no idea what should I use to create the timer, the backend or the frontend. Also how to implement it? Thanks! -
Django 2.1 passing a variable to template,
Have a question here about passing a variable into a Django template. The goal is to filter a set of photos based off the type of photography. I initially wanted to do it from S3 and the folder that it was in, but that's a little beyond my skill at the moment. I went with just creating different url's that account for that. The issue I'm having is that I'd like to pass the variable into the template that extends the base_layout.html, but it won't render anything for that variable. Am I just miss-understanding how to do it? Model.py from django.db import models # Create your models here. class Gallery(models.Model): title = models.CharField(max_length = 50) body = models.TextField(max_length = 500) created = models.DateTimeField(auto_now_add = True) thumb = models.ImageField(default = 'default.jpg', blank = True) slug = models.SlugField(blank = True) order = models.CharField(max_length = 2, blank = True) def __str__(self): return self.title def body_preview(self): return self.body[:50] class photoUrl(models.Model): url = models.CharField(max_length = 128) uploaded_on = models.DateTimeField(auto_now_add = True) class Photos(models.Model): title = models.CharField(max_length = 50) picture = models.ImageField(blank = True) created = models.DateTimeField(auto_now_add = True) catagory = models.CharField(max_length=256, choices=[('wedding', 'wedding'), ('portrait', 'portrait'), ('landscape', 'landscape'), ('boudoir', 'boudoir'),], blank = True) def __str__(self): return … -
Saving an unknown object type into database in Django
I have the following model: class Parameter(models.Model): par_type = = models.CharField(max_length=30) value = models.TextField() Majority of the time the value field will store a number (value=3.2118). But sometimes I want to assign a list of other object IDs (like value="[32, 22, 45]") or a string object (like value="pass"), etc. I will use value field in functions like the ones below based on the value of par_type: def foo(par): # par is a Parameter object. return float(par.value) / 2 def bar(par): # Some code to convert a par to a list of objects object_list = get_objects(par) # Return a random object from list return random.choice(object_list) I don't want to write a piece of code for every possible object type. Ideally there is one decompose() function to use everywhere. I thought of saving object as pickle or JSON type (saw it from here). But I couldn't figured out how to do it. I'm using MySQL db. -
Replacing long polling with message broker for a django app
I have django rest api which among other things have messaging functionalities. Currently the get messages for an user and get all rooms for an user are being done by long polling every 10 seconds. I want to change this to a message broker architecture. Can someone conceptually help me understand how does a message broker work and who calls the get endpoints based on what? -
Django Admin Extra Fields In get_queryset
I have Django 1.11 app that tracks Phones, Sim Cards, Data Usage of Sim Cards and the association of a Sim Card to a Phone like the following: #model to display information for all Phones class Phone(models.Model): serialnumber = models.CharField(max_length=255) brand = models.CharField(max_length=255) #model to display information for all sim cards class Sim(models.Model) iccid = models.CharField(max_length=255) msisdn = models.CharField(max_length=255) #model to display daily data usage for all sim cards class DataUsage(models.Model) date = models.DateTimeField() sim = models.ForeignKey(Sim) data_usage_can = models.FloatField() data_usage_us = models.FloatField() data_usage_other = models.FloatField() #model to make an association from a phone to a sim. This will include sims with no phones and phones with no sims as well #all sims and phones are unique class Association(models.Model): phone = models.ForeignKey(Phone) sim = models.ForeignKey(Sim) transaction_date = models.DateTimeField() My goal is, in the Django Admin page of the Association model, to display two additional fields that are not in model itself, namely "Cycle to Date Usage" (ctd_usage) and "Transaction to Date Usage" (t_usage). ctd_usage should get all data usage for a sim from the 1st of the current month, up to the current date, and t_usage should get all data usage for a sim from the 1st of the month … -
Django: Displaying appointment linked to a particular user on their profile only
I have a model in Django called 'Booking' to book appointments, where there are two user fields: an expert, and a user which both have ForeignKey relationships. I also have a CustomUser model and each user has a profile page. How can I specify that I want to view only the appointments linked to that particular user (or expert) on their profile page? models.py: class Booking(models.Model): user = models.ForeignKey(CustomUser, null=True, default='', on_delete=models.CASCADE) expert = models.ForeignKey(CustomUser, null=True, default='',on_delete=models.CASCADE, related_name='bookings') title = models.CharField(max_length=200, default='Video call with ..', null=True) start_time = models.DateTimeField('Start time') end_time = models.DateTimeField('End time') notes = models.TextField('Notes', help_text='Please provide some detail on what you would like to learn or discuss', blank=True, null=True) views.py: class BookingView(CreateView): model = Booking form_class = BookingForm def view_profile(request, pk=None): if pk: user = CustomUser.objects.get(pk=pk) else: user = request.user args = {'user': user} return render(request, 'profile.html', args) The profile displays all of the user objects fine, but I'm not sure how to call the user-linked booking objects only on the profile page. Any help would be appreciated!! -
Django Database Settings Reading From Base File
I have my Django application configured to use sqlite in the base settings file and I overwrite the setting in the production and development settings files. I set DJANGO_SETTINGS_MODULE to the correct value in my Dockerfile. However, when I run it, it uses sqlite as defined in the base settings file. If I comment it out I it complains about database.ENGINE not being set. Why is it reading the database configuration from the base.py settings file rather than the other? I specify the other in the environment variable and it's reading other settings from there but for the database it reads it from the base file. I'm somewhat confused by this behavior, if anyone could give me some direction towards solving this issue it would be appreciated. If you need any more information let me know. -
A custom argument in graphene-django
How do I create a custom argument in GraphQL with graphene-django? I currently have this configuration in my schema.py: class Post(DjangoObjectType): class Meta: model = FeedPost interfaces = (graphene.relay.Node,) filter_fields = ['id'] class Query(graphene.ObjectType): post = graphene.Node.Field(Post) def resolve_post(self, info, **kwargs): username = kwargs.get('username') u = User.objects.get(username=username) users_sources = FeedSource.objects.filter(user=u) return FeedPost.objects.filter(feed__feedsource__in=users_sources).annotate( source_title=F('feed__feedsource__title') ) schema = graphene.Schema(query=Query) But I have not been able to figure out how to make "username" a required argument in the actual GraphQL query on "post". -
How to restart heroku app without killing unfinished celery tasks
I have a django web application on heroku in which several celery tasks may be running in the background. Redis is used as a broker. The problem is, that when I restart the heroku application either with heroku restart or by deploying with heroku container:release while some tasks are being executed, they are killed with SIGTERM which means the tasks are never finished. 2018-11-23T19:35:24.506833+00:00 heroku[beat.1]: Restarting 2018-11-23T19:35:24.507645+00:00 heroku[beat.1]: State changed from up to starting 2018-11-23T19:35:24.517551+00:00 heroku[web.1]: Restarting 2018-11-23T19:35:24.518013+00:00 heroku[web.1]: State changed from up to starting 2018-11-23T19:35:24.528684+00:00 heroku[worker.1]: Restarting 2018-11-23T19:35:24.529175+00:00 heroku[worker.1]: State changed from up to starting 2018-11-23T19:35:24.952139+00:00 app[worker.1]: 2018-11-23T19:35:24.952156+00:00 app[worker.1]: worker: Warm shutdown (MainProcess) 2018-11-23T19:35:24.949622+00:00 heroku[worker.1]: Stopping all processes with SIGTERM 2018-11-23T19:35:24.996307+00:00 heroku[worker.1]: Process exited with status 143 2018-11-23T19:35:25.456920+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2018-11-23T19:35:25.480748+00:00 app[web.1]: [2018-11-23 19:35:25 +0000] [16] [INFO] Handling signal: term 2018-11-23T19:35:25.481026+00:00 app[web.1]: [2018-11-23 19:35:25 +0000] [19] [INFO] Worker exiting (pid: 19) 2018-11-23T19:35:25.481491+00:00 app[web.1]: [2018-11-23 19:35:25 +0000] [20] [INFO] Worker exiting (pid: 20) 2018-11-23T19:35:25.481519+00:00 app[web.1]: [2018-11-23 19:35:25 +0000] [21] [INFO] Worker exiting (pid: 21) 2018-11-23T19:35:25.623274+00:00 heroku[web.1]: Process exited with status 143 2018-11-23T19:35:25.816061+00:00 heroku[beat.1]: Stopping all processes with SIGTERM 2018-11-23T19:35:25.928498+00:00 heroku[beat.1]: Process exited with status 143 From what I found on the internet, the warm shutdown caused … -
Why am I getting an error pushing django code to heroku?
When I try to push my code for a Django site to Heroku, I am getting the following error: remote: /usr/bin/ld: /app/.heroku/python/lib/libpython3.6m.a(ceval.o): relocation R_X86_64_PC32 against symbol `_Py_NoneStruct' can not be used when making a shared object; recompile with -fPIC remote: /usr/bin/ld: final link failed: Bad value remote: collect2: error: ld returned 1 exit status remote: error: command 'gcc' failed with exit status 1 remote: remote: ---------------------------------------- remote: Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-hq2rsseo/mod- wsgi/setup.py';f=getattr(tokenize, 'open', open) (__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-4wci3c07-record/install-record.txt --single-version- externally-managed --compile" failed with error code 1 in /tmp/pip- build-hq2rsseo/mod-wsgi/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to stormy-stream-43261. remote: To https://git.heroku.com/stormy-stream-43261.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/stormy- stream-43261.git' I think it has something to do with Heroku not supporting some dependency, but regardless, I can't figure out what to do to resolve this issue. Any ideas? -
python-crontab ask for privileged user in django request
I'm trying to automate crontab to receive a request and create a job from django and I'm get the following error: Traceback: File "/var/www/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/var/www/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/var/www/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/var/www/myweb/apps/general/views.py" in create_cronjob_json 779. return create_cronjob(request) File "/var/www/myweb/apps/utilities/daemons_planner.py" in create_cronjob 12. cron = CronTab(user="pedro") File "/var/www/venv/lib/python3.6/site-packages/crontab.py" in __init__ 227. self.read(tabfile) File "/var/www/venv/lib/python3.6/site-packages/crontab.py" in read 288. raise IOError("Read crontab %s: %s" % (self.user, err)) Exception Type: OSError at /create-cronjob-json/ Exception Value: Read crontab pedro: b'must be privileged to use -u\n' I am using python-crontab This is my code: def create_cronjob(request): received_json_data = json.loads(request.body) cron = CronTab(user="pedro") comment = received_json_data['name'] command = received_json_data['command'] band = True for job in cron: if job.comment == comment: band = False if band: job = cron.new(command=command, comment=comment) job.setall(received_json_data['cron']) cron.write() response_data = {} response_data["success"] = True return JsonResponse(response_data) What might be the problem? How could I tackle the issue? -
Django - Admin - Dependent fields
in my django-admin detail i have two select fields (foreign keys): Via the first one i can select a Customer (object) Via the second one i can select a CustomerAddress (object) When i select the Customer A, i only want to present customer addresses which belong to this specific Customer A. When i select the Customer B, i only want to present customer addresses which belong to this specific Customer B. But django-admin loads all customer_addresses into the second select field. How can i make these two fields dependent on each other? thanks and greetings! -
Djano - right way to join not-django tables
I have old cms database, structure isn't perfect and it can't be modified but i need to query using django TABLE posts (post_id) TABLE posts_text (post_id, post_text) TABLE episode (id, season_id, episode_name) TABLE episode_post_relationship (id, season_id, episode_id, post_id) Please help me to create django models with right fields reference. Should i use OneToOneField, ForeignKey, ManyToManyField and etc or pure join? I'm trying to get Episodes from episode_post_relationship table with posts_text.posts_text and posts.some_other_col but can't specify that episode_post_relationship table should join posts_text on post_id and the same for posts table. -
I get an error list that says this field is required
this is the forms page from django import forms from django.contrib.auth.models import User from .models import Profile class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput, required=False) class Meta(): model = User fields = ['username', 'email', 'password'] class ProfileForm(forms.ModelForm): class Meta(): model = Profile fields = ['pic'] & this is the views page from django.shortcuts import render from .forms import UserForm, ProfileForm def register(request): if(request.method == 'POST'): userform = UserForm(request.POST) profileform = ProfileForm(request.POST) if(userform.is_valid() and profileform.is_valid()): user = userform.save() user.set_password(user.password) user.save() profile = profileform.save(commit=False) profile.user = user if('pic' in request.FILES): profile.pic = request.FILES['pic'] profile.save() else: print(userform.errors, profileform.errors) else: userform = UserForm() profileform = ProfileForm() return render(request, 'register.html', {'userform':userform, 'profileform':profileform}) when I submit the password or the picture it doesn't save the user to the admin area and says that password is required and the picture is not uploaded -
Django: Check if value in list
I have a QuerySet with several entries order.order_items.all. I want to check in my template if any of these items in my list contain the foreign_key discount. After one is found, I want to display that a discount_code was used for the order. How would you solve this? Example: <QuerySet [OrderItem: #k9ukvrfvjk - 1x Test Ticket 1, OrderItem: #k9ukvrfvjk - 1x Test Ticket 2]> -
Django and python - different versions
i' ve an application running quite long time ago with python 2.6.6 and django 1.4.5 . It' s running on apache2 and debian (of course it uses virtualenv). I' d like to add another application onto that server, but with python 3.4.5 and django 1.9(+). They' d have of course a different virtualenvironment, even a different domain, however i' d like them to use the same db. My question would what kind of complications will i face? For instance different table layout for django tables, no south anymore, but migrate, etc. Are these problems even overcomeable? Thanks. -
Django rest framework+jquery error handling
I've created api using django rest framework. In frontend used jquery to process some inter activity. Using jquery ajax I have done most of the part. But problem is error handling. Want to show error if validation failed. How can I do that easily? -
Error importing data to a model in Django
I´m trying to import data from a csv file to a Django model. I´m using the manage.py shell for it with the following code: >>> import csv >>> import os >>> path = "C:\\Users\Lia Love\Downloads" >>> os.chdir(path) >>> from catalog.models import ProductosBase >>> with open('FarmaciasGob.csv') as csvfile: ... reader = csv.DictReader(csvfile) ... for row in reader: ... p = Country(country=row['Country'], continent=row['Continent']) ... p.save() ... >>> >>> exit() I get the following error message at a given point of the dataset: UnicodeDecodeError: "charmap" codec can´t decode byte 0x81 in position 7823: character maps to (undefined) For what I could find, it seems to be a problem with the "latin" encoding of the csv file. Inspecting the csv, I don´t see nothing special about the specific row where it get´s the error. I´m able to import about 2200 rows before this one, all with latin characters. Any clues? -
Django 2.1 using TinyMCE 4 as the email template editor, but how do I get it to upload images easily?
I am new to Django 2.1 and need to create an admin site to manage and edit email communication templates. The content is stored in a text area field. I tried using TinyMCE both with the JS link and installing Django-TinyMCE and FileBrower to be a full blown WYSIWYG editor to allow for formatting. But, I cannot get it to work using either method to upload images. I followed many steps provided in the TinyMCE website and in other Stack members’ answers. Can someone help? -
Django: constant 3rd party api data stream into frontend?
I'm building an application on react/django that requires me to have a live stream of real time weather information presented to a user. Currently my app gets a snapshot of information whenever a user loads the page via axios request to my django backend that makes an api call and return the weather back at that given time. Only when a user reloads the page can I get new weather information. I've done some reading and it seems that I might want to look into django channels. Is this a proper/standard flow for apps streaming information live from 3rd party sources? I imagine having a websocket connection between react and django, and django having some logic for an api call every set interval - returning that data back to react. If so, where in my django-channels consumer would I have this interval logic? And what is the best way to run an api call every (1 second) in django? Would it be in my Consumer's connect definition? Ideally I'd only like the user to have to send one automatic request on page load that begins the socket connection and have weather information streamed back based on what states the user …