Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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"> … -
Order data from database by two dates in django
I have a problem with ordering two dates in django model. I have a model which keep records of the document like below: class Document(models.Model): document_title = models.CharField(max_length=100) document = models.FileField() date_of_signature = models.DateField() date_of_rectification = models.DateField(null=True, blank=True) class Meta: ordering = ['-date_of_signature', '-date_of_rectification'] I have used the class Meta Options.ordering to order date and got result with ordering, but my specific problem is that: Ordering should be based on both fields if both fields have the date. But date_of_rectification can be a null value, so if it is null then ordering must be with latest date_of_signature which I didn't get with class Meta Options.ordering I have searched many questions on stackoverflow and found this MySQL query Mysql order items by the newest of 2 dates which exactly solved my problem in MySQL database and implemented this query on django Manager.raw() as below I got expected result. But this didn't help me on ordering data on Django Admin which is not my requirement. And also I want to know if this query could be solved using django Queryset insted of RawQueryset. Model.objects.raw("""SELECT * FROM document ORDER BY IF(date_of_rectification > date_of_signature, date_of_rectification, date_of_signature)""") -
Django translation check without running the project
Is there a simple way to check the correctness of translations in django.po file? (I don't mean to check it in the running project) -
Django bootstrap and paragraph
I'm facing a problem using Django / Bootstrap / RichText. When I start using Styles in CKEditor, my bootstrap style goes bad. In fact when I'm using several <p></p>, my layout goes wrong. My HTML File : {% for rule in rules %} <div class="content-section"> <div class="row bg-info"> <div class="col-sm-12 text-white"> <i class="fas fa-greater-than"></i> <a class="text-white" href="{% url 'rule-detail' rule.pk %}">{{ rule.title }}</a> </div> </div> <div class="row"> <div class="col-sm-2 align-middle text-center font-weight-bold"> {{ rule.reference }} </div> <div class="col-sm-10 text-justify"> {{ rule.content|safe|truncatechars:250 }} </div> </div> </div> <hr> {% endfor %} Rule source example : <p><cite>Style1</cite></p> <h1><cite>Style2</cite></h1> <p><cite><img alt="" src="https://i.kinja-img.com/gawker-media/image/upload/s--SGs2aMWj--/c_scale,f_auto,fl_progressive,q_80,w_800/jgpeuoavmn7pwbh98ycs.jpg" /></cite></p> <p>text here <strong> text there</strong> lorem ipsum</p> the first article is well displayed, but the second is shifted How can I handle this ? Thanks, -
How to retrieve a certain number of objects using Django Queryset
I need to obtain multiple objects(minimum 1, maximum 5) using the query - Document.objects.all().order_by('uploaded_at') I want to show the latest 5 or less objects. Any ideas? -
Django CMS: Plugin to app without ForiengKey
I'm new in CMS Django, and I'm trying to create a plugin which will be connected to Blog app. I want to show on every page 5 newest blog articles. Problem is that every plugin instance must be connected to some instance from blog app, because in our template we will use instance of plugin like: instance.article.all() or instance.blog.article.all(). Is some option to get instances of Article into the template of my BlogPlugins template without using instance of BlogPlugin? Thank you. -
Django logs with custom filter for username
I tried to create custom logging filter to log the username for each request like in the following link : django logging - django.request logger and extra context But my request has no user attribute. here is my code: class RequestUsernameFilter: def filter(self, record): request = record.request record.username = request.user.username return True The request attribute: AttributeError: 'socket' object has no attribute 'user' -
Mocking a SMS sending function in a class view Django
I am writing a Django class view that is supposed to run a few database checks, then create an object and send some information via SMS. The class is as follows: class MyClass(GenericAPIView): def send_info(content, number): send_sms(content, number) def post(self, request, *args, **kwargs): #... Do a bunch of stuff send_info(content, number) return Response(status=200, data="Request processed") Now I would like to test the view, of course I can't check whether and which the SMS is received. I do have a developement variable in settings.py that make sure for the moment that the info is just printed on screen, but I would like to use the unittest.mock library to write a test that simply checks whether send_info() is called, so that I won't be bother checking what info is passed (which is random). How would I go about it?