Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing a related object from a different database in Django
Consider the following two related models, User and Tier: class User(models.Model): tier = models.OneToOneField(Tier) class UserTier(models.Model): tier = models.IntegerField(related_name='tier') Suppose there are two databases, 'default' and 'replica', and we have an instance user of User. I assume that the default related field lookup, user.tier, would use Django's default router to look up the UserTier in the default database. One could do UserTier.objects.using('replicate').get(user=user) similar to https://docs.djangoproject.com/en/2.1/topics/db/multi-db/#manually-selecting-a-database-for-a-queryset, but this seems inefficient as we are querying all UserTier objects instead of just looking up the related one-to-one field. Is there a way to do the related object lookup directly, something like (in pseudocode) user.tier(using='replica')? -
module path in uwsgi is one layer up - how to indicate that
My initial uwsgi.ini location looked like this parent |-uwsgi.ini |_main | |_wsgi.py |_scripts Since uwsgi.ini was right next to the main folder I had this parameter in my uwsgi.ini and it worked module=main.wsgi <---This works since it was next to main Now I just moved the uwsgi.ini file into the scripts folder so its no longer right next to the main folder that contains wsgi.py. Because of that I had to change the module parameter in the file. This is the new parameter module=../main.wsgi <----This does not work since its not next to main anymore - What do I do ? I think this is wrong as I am getting an error. I am not sure how to indicate the module path now that I moved the wsgi.ini into the scripts folder. Any suggestions ? -
Python loop interrupted by time.sleep
I am facing a weird issue in my python (django) app. I have implemented my method to change flags I have in firebase. But I wanted my method to wait for a few seconds before changing another flag. My method without the two time.sleep(10) lines works perfectly. But when I put them there for some reason it only iterates each loop one. This is my code: def gameController(session_id): db = firestore.client() round_col = db.collection(u'Session').document(session_id).collection(u'Rounds') round_docs = round_col.get() iCounter = 0 jCounter = 0 for i in round_docs: iCounter += 1 round_ref = round_col.document(i.id) question_col = round_ref.collection(u'Questions') question_doc = question_col.get() for j in question_doc: jCounter += 1 #time.sleep(10) question_ref = question_col.document(j.id) question_info = question_ref.get().to_dict() question_info['isDoneSubmitAnswer'] = True question_ref.set(question_info) #time.sleep(10) question_info = question_ref.get().to_dict() question_info['isDoneChooseAnswer'] = True question_ref.set(question_info) round_info = round_ref.get().to_dict() round_info['isDone'] = True round_ref.set(round_info) return (iCounter, jCounter) It really does not make sense to me. The method returns (1,1) if I uncommented both of time.sleep(10) lines. If I uncommented only one of them it returns (2,6). If I keep it as is it returns (3,9) which is the correct behavior. In this firebase session, I have 3 different Rounds and 3 different questions within each round. Thank you guys. -
How do I implement a U2F login process into Django?
I've been researching around on how to implement U2F hardware authentication into a Django application. The documentation for libraries such as a python-based Yubico one seem like they are missing some important information (located here) or I am misunderstanding something. According to this picture on their official documentation, you are supposed to follow the workflow where you first verify username and password then issue a challenge (a public key I think?) server-side. Next, you pass that challenge up to the u2f-api.js javascript library, client-side (documentation for javascript library here and here) where it invokes u2f.sign() or u2f.register() methods. After that, the client side handles the magic of inserting the hardware key and touching it then passes a response back down to the server. Where I am stumped is what python code do I need to call to actually create a challenge and/or register and store the device information ?? Any and all help is welcome to point me in the right direction. Please correct me if I am wrong about anything too. -
How to use one model as source for 'choices' in another model?
I have 3 models: User, UserProfile and Programme. User holds the names of all users; class User(AbstractUser): first_name = model.Charfield(...) last_name = model.Charfield(...) ... UserProfile contains the attributes associated with each user (e.g. sales manager(sm), program manager(pm), delivery manager(dm) etc. class UserProfile(model.Model): user = model.ForeignKey(User, on_delete...) sm = model.BooleanField(default = False, editable=True...) pm = model.BooleanField(default = False, editable=True...) dm = model.BooleanField(default = False, editable=True...) A User may have any combination of UserProfile attributes. For example: User-1: sm User-2: sm, pm User-3: dm User-4: sm, dm ... Every programme in Programme must have a user assigned for each of sm, pm, dm so my challenge is finding a way to generate a 'choices' list for each of sm, pm and dm limited to Users with the appropriate attribute. class Programme(model.Models): programme_name = models.Charfield(...) AND ESSENTIALLY: sm = only users with userprofile.sm = True pm = only users with userprofile.pm = True dm = only users with userprofile.dm = True I've tried adding a function to UserProfile then referencing it in Programme: UserProfile(model.Models): .... def get_pm(self): pm_list = [] pm = UserProfile.objects.filter(pm=True) for i in pm: pm_list.append(i.user.last_name) return pm_list and in Programme: Programme(model.Models): pm = models.Charfield(choices=UserProfile.get_pm, ... but this generates the error: … -
How to use SlugRelatedField for incoming request (deserialise) and full serialiser for response for related fields
My db model is of events and each event is connected to a venue. When I retrieve a list of events I use: venue = VenueSerializer(read_only=True) When I post to my drf endpoint I use: venue = serializers.SlugRelatedField( allow_null=True, queryset=Venue.objects.all(), required=False, slug_field='id') However this causes that in the response I recieve from the post request, the venue is serialised as a slug field. I want it to use the VenueSerialiser for the response. I came accross https://stackoverflow.com/a/49035208/5683904 but it only works on the Viewset itself. #serializer_class = EventSerializer read_serializer_class = EventSerializer create_serializer_class = EventCreateUpdateSerializer I need to build this functionality into the serialiser itself since it is shared with other components. -
Poor Performance for Form Rendering In Django 1.11
My site has a navbar with an advanced search widget (beside the search field), which renders on every page. For each request, a context_processor creates the form so it can be available on that page in the navbar. This form has about a dozen selects with a total of several hundred options. Most of those options are for the currency and country selects, along with about 80 other options. There is an even larger list for "stores" but it is loaded via AJAX so it should not be a factor here. Performance was fine on Django 1.8, but after upgrading to 1.11 I noticed with NewRelic that 200+ ms are now being used between the following: Render/django/forms/widgets/select_option.html Render/django/forms/widgets/select.html Render/django/forms/widgets/attrs.html This seems to be related to 1.11's change to Template-based Widget Rendering, however the only pages I could find talking about related problems were about Django Toolbar which I do not run in production. I am and already using the Cached Template Loader (which is now default), however I don't know if this helps here. I cannot easily cache this form because as you can see in the code, I set a number of defaults based on the request. Why is … -
whats does assert _sre.MAGIC == MAGIC, SRE module mismatch AssertionError: SRE module mismatch error mean?
Hello I´m trying to run a python manage.py runserver command but getting this error message File "C:\Users\adrie\Anaconda3\lib\sre_compile.py", line 17, in assert _sre.MAGIC == MAGIC, "SRE module mismatch" AssertionError: SRE module mismatch Does anyone have idea of what´s happening here? I had anaconda installed previously and was running fine. But then I´ve deinstalled and reinstalled anaconda, and I´m getting this error now. -
Can't do nothing with manage.py
When I perform any action on manage.py I get this output: Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/usr/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 296, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: auth_user 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/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/usr/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/usr/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/vyorner/weaver/main/models.py", line 11, in <module> class AbstractPost(models.Model): File "/home/vyorner/weaver/main/models.py", line 17, in AbstractPost default=User.objects.get(pk=2) # a.k.a. anonymous user File "/usr/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python3.7/site-packages/django/db/models/query.py", line 393, in get num = len(clone) File "/usr/lib/python3.7/site-packages/django/db/models/query.py", line 250, in __len__ self._fetch_all() File "/usr/lib/python3.7/site-packages/django/db/models/query.py", line … -
Create a document using python-docx and send as attachment through django
I have created a document using docx and tried to send as an email attachment without saving the document on the server. Below is my code: Document = document() paragraph = document.add_paragraph("Test Content") f = BytesIO() document.save(f) file_list = [] file_list.append(["Test.docx",f, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"] email = EmailMessage(subject = 'Test', body = 'Hi', to = ['test@test.com'], attachments = file_list) email.send() I am getting the following error: TypeError: expected bytes-like object, not BytesIO on the line email.send() I tried converting BytesIO to StringIO as mentioned here f = f.read() f = StringIO(f.decode('UTF-8')) and then I get the error: TypeError: expected bytes-like object, not StringIO I looked at the solution from this, but didn't understand how the document is sent as an attachment. Any help or pointers is appreciated. Thanks! -
Unable to locate static files django and neither they are working on deployment
Unable to locate static files After doing python manage.py collectstatic I got this message static files copied to '/home/tousif1122/project/Freelancing/staticfiles', 129 unmodified. My site is http://tousif1122.pythonanywhere.com/ on pythonanywhere . On local machine when I am doing http://127.0.0.1:8000/static/style.css its working but not on this address . My setting.py file is PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] -
How to install a modified python package
I have modified the django-import-export package, now I need to upload my application to Heroku and use the modifications that I have made. I have created a github repository and uploaded the files of the folder import_export. Now How can I use this modificated package into my project? -
error with an url that does not exist in my project in django
I was having this issue just in my production environment. I have an icon that is in my static files. I can load it through https://mydomain/static/img/favico.ico, but at the same time I get a 500 error for the following url https://mydomain/favico.ico . <- this url does not exist in my project. I can't replicate in my local environment. I already did collectstatic. -
How does django match MySQL datatypes?
I am still new to Python Django and stumbled across something I don't understand. First of all, a snippet from my model: (trimmed all others fields...) class AircraftTypes(AbstractBaseModel): ... engines_count = models.PositiveSmallIntegerField(default = 1) ... Here a screenshot from MySQL Workbench created after the migration process. Screenshot_MySQL_Workbench I would have expected to see something link UNSIGNED TINYINT or so but why is Django creating a VARCHAR(1)? Not surprisingly, when I try to enter a number like 103 it fails with MySQL error "1406. Data too long for column". Can someone enlighten me what is going on here, please? By the way, I would not mind that much that numbers are stored as text since it will work but maybe not as efficient. But what I don't unterstand is where the limit to one character comes from. Is it my default value that is turning crazy? Please help!!! Florian -
Unsupported lookup 'iexect' for CharField or join on the field not permitted
Could anyone tell me why I get a FieldError class RegisterForm(forms.Form): username = forms.CharField(max_length=35, label="Username eintragen") password = forms.CharField(min_length=6, max_length=50, label="Password eintragen", widget=forms.PasswordInput) email = forms.EmailField(label="Email eintragen") def clean_username(self): username = self.cleaned_data["username"] if User.objects.filter(username__iexect=username).exists(): raise forms.ValidationError("Diesen Usernamen gibt es schon") return username Unsupported lookup 'iexect' for CharField or join on the field not permitted. -
django UserCreationForm doesn't save
gentlemans i've got a problem with the user registration, data is not saved to model Profile, everything is saved only in Users, i think that signals's work incorrect views.py from django.shortcuts import render, redirect from .forms import UserRegisterForm from .models import Profile from django.contrib import messages from django.contrib.auth.decorators import login_required def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, 'Your account has been created') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form':form}) models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to = 'profile_pics') def __str__(self): return f'{self.user.username} Profile' forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] signals.py from django.dispatch import receiver from django.db.models.signals import post_save from django.contrib.auth.models import User from .models import Profile @receiver(post_save, sender=User) def create_profile(instance, sender, **kwargs, created): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() -
Django: creating number of forms dynamically
so I want to create a dynamic number of forms depending on a variable. Here is my forms.py class CTestform(forms.Form): def __init__(self, c_test_tokens, *args, **kwargs): super(CTestform, self).__init__(*args, **kwargs) wordsbeforegap = '' iteratorforgaps = 0 for i in (0, len(c_test_tokens)-1): if '#GAP#' not in c_test_tokens[i]: wordsbeforegap = wordsbeforegap + c_test_tokens[i] else: self.fields[iteratorforgaps] = forms.CharField(widget=forms.TextInput(attrs={'size': '5'}), required=False, label=wordsbeforegap, label_suffix='') wordsbeforegap = '' iteratorforgaps += 1 Here is my views.py where I call CTestform to render: def ctest(request): # this function is not really important for the question # c_test_tokens = list of chars c_test_tokens, gaps, tokenindexe = generate_c_test(exampletext()) form = CTestform(c_test_tokens=c_test_tokens) return render(request, 'ctest.html', {'form': form}) I thought that the forms created would be in self.fields, so to print the forms at my website I have in my html this: <div class="ctest"> {% for forms in form.fields %} {{ forms }} {% endfor %} </div> But the site is empty and no forms are getting rendered. What could be the problem? -
Django form DateField initial value not updating
In my form I have a field that I want to default as Today when launching the form: class ExpenseForm(forms.ModelForm): date = forms.DateField(initial=datetime.now(), widget=forms.DateInput(attrs= {'id':'datepicker'})) Now if I go to the form I see it working correctly, it's got today's date populated, (for example "2018-12-03") but then when I come in tomorrow, it STILL has yesterday's date populated. In fact it will not update until I somehow restart the server. Any idea? Thank you. -
How to pass a list/tuple into an environment variable for Django
anybody know how I can pass a list into an environment variable? At the moment I am trying to put a list of codes into my settings.py file. I have this in my .env file: ALLOWED_CODES='AB01', 'AB02' In my settings.py this is what I have: ALLOWED_CODES = [os.environ.get('ALLOWED_POSTCODES')] If run docker-compose config it is parsed as: ALLOWED_CODES: '''AB01'', ''AB02''' What I want is for it to return the exact list defined in the .env file. -
GraphQL get all fields query
I have made an api using DjangoREST an I have just started using graphQL. Currently, I can search a field and it will return the field requested. But I have ran across a problem where if I search a field and they are fields with the same result the query will return an error { "errors": [ { "message": "get() returned more than one -- it returned 2!", I followed a few tutorials and this is what my query format is like category = graphene.Field(CategoryType, id=graphene.Int(), name=graphene.String()) def resolve_category(self, info, **kwargs): id = kwargs.get('id') name = kwargs.get('name') if id is not None: return Category.objects.get(pk=id) if name is not None: return Category.objects.get(name=name) return None I was just wondering, are they ways I can make it so it will allow to return more than 1 result. So I put in dave and I can get all the daves from that model? -
Django-moderation need restart server everytime
I have a problem with django-moderation when I do not have visibility_column = 'visible' and column in model visible = models.BooleanField(default=False), rejected changes or models are displayed on the page, but when I use visibility_column = 'visible', theoretically everything works as it should, but I need to restart the server for these changes to be displayed or added. Someone can help me with thar ? I dont need solutions but only hints -
Error when pushing a project to Heroku: [remote rejected] master -> master (pre-receive hook declined)
I am using git and django and trying to push a python based project to Heroku. The error I'm getting (shown in title) has been explained a lot online, but the solutions (such as the most commonly linked one at 'Git push error pre-receive hook declined') do not help for someone trying to push using Heroku from what I can tell. I believe what I have to do is be able to push my master branch, which is protected, but I can not find out how to change so that "developers can push" on heroku (or something of that like). Thanks in advance!!!! Sam -
How to connect **MLAB mongodb from django
hi i am using below setting but it is not working DATABASES = { 'default': { 'ENGINE': 'mongodb://username:password@ds249605.mlab.com:49605', 'NAME': 'mlab1', } } getting an error like django.core.exceptions.ImproperlyConfigured: 'mongodb://username:password@ds249605.mlab.com:49605' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
How to retrieve previous/next entry in a Django DetailView view
I'm using a class based view DetailView to handle the layout of a blog post. In the template, I need to implement a button to show previous/next posts ordered by timestamp. For this reason, I need to override the context by customising the get_context_data(self) method. In the context I thus need to add the instances of prev/next entries by insertion_date relative to current post. views.py class EntryDetailView(DetailView): model = Entry def get_context_data(self, **kwargs): context = super(EntryDetailView, self).get_context_data(**kwargs) context['base_url'] = self.request.build_absolute_uri("/").rstrip("/") return context models.py from .managers import EntryManager class Entry(models.Model): """ Blog Entry """ insertion_date = models.DateTimeField('inserimento', auto_now_add=True) Thank you for any help you could provide. -
Django Recaptcha (v2) - using captcha in modal rendered by ajax
So I use this package: https://github.com/praekelt/django-recaptcha I render modal with for in AJAX-based list view: {% for object in object_list %} <div id="offer-{{ object.id }}" class="modal fade services-modal" role="dialog"> <div class="modal-dialog"> <div class="modal-content shadow"> <div class="offer-box"> <div class="offer-box-head"> <div class="offer-slider"> <div class="swiper-wrapper"> {% if object.gallery.all %} {% for item in object.gallery.all %} {% thumbnail item.photo "800x530" crop="center" as img %} <div class="swiper-slide"><img src="{{ img.url }}" alt="offer image"></div> {% endthumbnail %} {% endfor %} {% else %} <div class="swiper-slide"><img src="{% static 'img/blank.png' %}" alt="offer image"></div> {% endif %} </div> <div class="offer-pagination-prev left-arrow"> <span class="ti-angle-left"></span> </div> <div class="offer-pagination-next right-arrow"> <span class="ti-angle-right"></span> </div> </div> <span class="offer-box-price">{{ object.price|floatformat:2 }} PLN</span> {% if object.featured %} <span class="offer-box-label"><span class="ti-star"></span>Polecane</span> {% endif %} </div> <div class="offer-content pl-30 pr-30"> <span class="h4 offer-box-title">{{ object.offer_type }} {{ object.surface|floatformat }}m2</span> <span class="offer-box-location"><span class="ti-location-pin"></span>{{ object.locality }}: {{ object.street }} </span> {% if object.year_built %} <span class="offer-box-meta">{{ object.year_built }}</span> {% else %} <span class="offer-box-meta">Brak daty zbudowania</span> {% endif %} <a class="close" data-dismiss="modal"><span class="ti-close"></span></a> <div class="contact-form mt-60"> <form method="post" action="{% url 'confirm_mail' %}"> {% csrf_token %} <div class="form-group"> {{ form_mail.author.errors }} <label for="{{ form.author.id_for_label }}">Autor</label> {{ form_mail.author }} </div> <div class="form-group"> {{ form_mail.email.errors }} <label for="{{ form.email.id_for_label }}">Email</label> {{ form_mail.email }} </div> <div class="form-group"> …