Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fade used objects in django admin
I am trying to avoid having the same foreign keys assigned to an object. A short example would be: #models.py class Newspaper(models.Model): article = models.ForeignKey(Article) release_date = models.DateField(default=date.today) end_date = models.DateField() class Article(models.Model): name = models.CharField(max_length=100) text = models.TextField() I do not want to have the same article in newspapers that are out at the same time. end_date is the date, when the paper is not relevant, so it is ok to release the same article there as well. I know, I can put validators to avoid using the same article twice for a certain time period, but is it possible to make the text of the already published articles for this time period unselectable (faded as well) or somehow visually differentiable? -
How to download text file from url and store it in django project directory
I use django 1.11 and python 3.6 I have several text file links Example: http://mylinks/telechargement.php?file=file1.txt http://mylinks/telechargement.php?file=file2.txt Now It's possible to download it with python code ? How can I download each of these files via the link and save it to a specific directory with python code without modifyin its structure ? Thank for advance. -
Migrate SQLite3 database to MySQL in Django
I am developing a website using Django 1.11 and Django-CMS with python3. Initially I used the default database sqlite3, however, now I want it to migrate to mysql. I have found several solutions online like Solution 1 Solution 2 However, both did not work. For the first solution I got the following error: AttributeError: 'Page' object has no attribute '_node_cache' and for the second solution there was this error: Could not load contenttypes.ContentType(pk=1): (1062, "Duplicate entry 'cms-placeholder' for key 'django_content_type_app_label_model_76bd3d3b_uniq'" In both examples, I used a empty database and migrated first. Any help please? -
RuntimeWarning: DateTimeField received a naive datetime for auto_now
We're using Django 1.10 We're getting a lot of this warning: RuntimeWarning: DateTimeField Item.updated_at received a naive datetime (2018-05-01 12:35:18.213471) while time zone support is active. RuntimeWarning) I read a lot of answers about that questions, but in that case we're not settings the date manually. That field (Item.updated_at) is set as auto_now=True Is there a way to make 'auto_now' not naive? This is part of the model: class BaseModel(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True, unique=True, primary_key=True) created_by = models.CharField(max_length=200) created_at = models.DateTimeField(db_index=True, auto_now_add=True) updated_by = models.CharField(max_length=200) updated_at = models.DateTimeField(db_index=True, auto_now=True) Thanks -
Django add permission to Urlrouter before view methods are called
urlpatterns = patterns('', url(r'^A/$', 'django.contrib.auth.views.login'), url(r'^B/$', logout_page), url(r'^C/$', c_method), url(r'^D/$', D_method),) In the above URL configuration, I would like allow only router A to particular set of users, and remaining B,C and D to particular set of user. how can I do this using URL configuration. Please note, my application already has got nearly 80 URL'S, now I cannot edit and add permission to each method. So what I am trying do is, as soon as URL is called, it need pass through the permission, before it actually calls views methods. Please let me know how can I do this. -
Hi. I am working on a django project
I want to include age field in my django models which accepts age of only those of 18 age or above. How do I do that? -
Django Key Error: KeyError at 'template.html' request when initiating a form
I'm working with Pinax-Stripe library, and I want to create a custom account for the logged in user. I'm trying to rewrite the CreateCustomAccountView() as a function based view. The reason for that, is that I don't understand where CreateBankAccountView comes from and it's nowhere to be seen in the GitHub code. So for simplicity, I have the following form: class Form(DynamicForm): # some form fields def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") views.py def view(request): if request.method == 'POST': form = Form(request.POST) else: form = Form() return render(request, 'dashboard/template.html', {'form': form}) I do have request in my template processor. I'm not sure why this happens and how it's possible to instantiate an empty form? -
django AttributeError, type object 'object' has no attribute python 3
got an error when post the data AttributeError at /system/create/ type object 'object' has no attribute 'EmpInstallment' Request Method: POST Request URL: http://127.0.0.1:8000/system/create/ Django Version: 1.11.2 Exception Type: AttributeError Exception Value: type object 'object' has no attribute 'EmpInstallment' Exception Location: /Users/wakanda/pyproject/payroll/system/views.py in form_valid, line 117 Python Executable: /Users/wakanda/py-virtualenv/payroll3/bin/python Python Version: 3.6.5 Python Path: ['/Users/wakanda/pyproject/payroll', '/Users/wakanda/py-virtualenv/payroll3/lib/python36.zip', '/Users/wakanda/py-virtualenv/payroll3/lib/python3.6', '/Users/wakanda/py-virtualenv/payroll3/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Users/wakanda/py-virtualenv/payroll3/lib/python3.6/site-packages', '/Users/wakanda/py-virtualenv/payroll3/lib/python3.6/site-packages/setuptools-39.0.1-py3.6.egg', '/Users/wakanda/py-virtualenv/payroll3/lib/python3.6/site-packages/configparser-3.5.0-py3.6.egg'] my model.py class Employee(models.Model): nik = models.CharField(max_length=100) name = models.CharField(max_length=100) def __str__(self): return self.name def get_absolute_url(self): return reverse("system:detail",kwargs={'pk':self.pk}) class EmpLoan(models.Model): status = models.BooleanField() nominal = models.DecimalField(max_digits=10, decimal_places=0) emp = models.ForeignKey(Employee, related_name='emploan') created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.emp.name class EmpInstallment(models.Model): nominal = models.DecimalField(max_digits=10, decimal_places=0) loan = models.ForeignKey(EmpLoan, related_name='empinstallment') created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.loan.emp.name my view.py class EmployeeCreateView(CreateView): fields = ('spl', 'status') model = models.Employee def form_valid(self, form): self.object = form.save(commit=False) try: pinjaman = models.EmpLoan.objects.get(emp_id=1, status=0) cicilans = models.EmpInstallment.objects.filter(loan_id=pinjaman.id).values_list('id', flat=True) totalcicilan = 0 for i in cicilans: cicilan = models.EmpInstallment.objects.get(id=i).nominal totalcicilan = totalcicilan + cicilan sisapinjaman = pinjaman.nominal - totalcicilan if ( 12 - cicilans.count()) != 0: cicilansekarang = sisapinjaman / ( 12 - cicilans.count()) else: cicilansekarang = 0 #potongan cicilan hasil = round(cicilansekarang) if hasil != 0: joe = models.EmpInstallment.objects.create(loan=pinjaman, nominal=hasil) object.EmpInstallment.add(joe) else: … -
Django notification when file was uploaded from Application X to Application Y
Please can someone help me out, i've a Django project that contains number of applications so i want any time an application inserts a file in to the DataBase a notification to the destined application..any clue? in general a notification or message whenever application X uploads file to application Y -
Return user_id as response of post api
I want to return user_id for each object created using post api I want output in form of [ {"info": { "status": "SUCCESS", "message": "User Details Successfully Uploaded" }, "user_id": 10001 } ] Here is my Code Serializer.py class UserDetailsSerializer(serializers.ModelSerializer): """docstring for UserDetailsSerializer""" class Meta: model = UserDetails fields = ['user_id', 'user_email', 'user_full_name', 'user_token', 'patient_id', 'user_preferences'] read_only_fields = ['user_id'] Views.py class UserDetailsViewSet(APIView): def get(self, request): queryset= UserDetails.objects.all() serializer_class=UserDetailsSerializer(queryset,many=True) return Response(serializer_class.data) def post(self, request): serializer_class_post=UserDetailsSerializer(data=request.data) if serializer_class_post.is_valid(): try: serializer_class_post.save() return Response([{"info": { "status": "SUCCESS", "message": "User Details Successfully Uploaded" }, "user_id": serializer_class_post.data }], status=status.HTTP_201_CREATED) except IntegrityError as e: return Response([{"info": { "status": "Error", "message": "Error Uploading User Details" } }], status=status.HTTP_400_BAD_REQUEST) return Response(serializer_class_post.errors, status=status.HTTP_400_BAD_REQUEST)` models.py class UserDetails(models.Model): user_id = models.IntegerField(primary_key= True) user_email = models.CharField(max_length=254) user_full_name = models.CharField(max_length=200) user_token = models.CharField(max_length=200) patient_id = models.CharField(max_length=12, unique=True) user_preferences = models.CharField(max_length=200) class Meta: managed = False db_table = 'walnut_users' def __str__(self): return self.user_id -
TemplateDoesNotExist at /polls/1/results/
I am following django 2.0 tutorial "2.6.2 Use generic views: Less code is better" and try to convert functions views to class views. It throws such an error TemplateDoesNotExist at /polls/1/results/ polls/question_detail.html Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/results/ Django Version: 2.0.4 I checked the code with the official materials class ResultsView(generic.DetailView): model = Question template = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): #Redisplay the question voting form return render(request, 'polls/detail.html', { 'question':question, 'error_message':"You did'nt select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) The errors occurs when I attempt to submit the vote: The 'polls/detail.html' template works proprely when come with the functions views <h1>{{ question.question_text }}</h1> {% if error_message %} <p> <strong>{{ error_message }}</strong> </p> {% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice {{ forloop.counter }}" value="{{ choice.id }}"/> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label> <br> {% endfor %} <input type="submit" value="Vote"/> </form> What's the problem with my code? -
Dockerized Django REST Framework / Postgresql - Cannot connect to server
When i try to execute the following command: sudo docker-compose run web python manage.py makemigrations I get the following error inside my terminal: Here is what my docker file looks like: FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /agent-technologies WORKDIR /agent-technologies COPY . /agent-technologies RUN pip install -r requirements.txt EXPOSE 8000 Here is what my docker-compose.yml looks like: version: '3' services: db: image: postgres environment: - POSTGRES_USER=stefan_radonjic - POSTGRES_PASSWORD=cepajecar995 - POSTGRES_DB=agent_technologies_db web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/agent-technologies ports: - "8000:8000" links: - db depends_on: - db And finally here are settings of PostgresSQL DB I have previously created : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'agent_technologies_db', 'USER': 'stefan_radonjic', 'PASSWORD': 'cepajecar995', 'HOST': 'localhost', 'PORT': '', } } -
Display form content on same template django
So I am working on django, I have a simple form with one text field named "sujet", here's the form.py code: from django import forms class ContactForm(forms.Form): sujet = forms.CharField(max_length=100, widget=forms.TextInput( attrs={ 'id': 'id_sujet', 'style': 'border-color: blue;', 'placeholder': 'Write your name here' } ) ) The template "contact.html" where the user can fill the form is the following: <form id="myForm" action="{% url 'contact' %}" method="post"> {{ form.sujet }} <input type="submit" value="Submit" /> </form> <div id="response"> Sujet : <span id="sujeet"></span> {{ sujet }} </div> In my "views.py" I want my contact function to render the variable "sujet" to the template so I can diplay it on "contact.html" after filling and submitting the form (the intended usage of this is later to display the result of the database query that concerns sujet and not the variable itself but I am still working on that), here's the code of the view function : def contact(request): form = ContactForm(request.POST or None) if form.is_valid(): sujet = form.cleaned_data['sujet'] envoi = True return redirect(request.META['HTTP_REFERER'], {'sujet':sujet}) else: return render(request, 'voirkpi/contact.html', locals()) Here is the code of my "urls.py" : from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('accueil', views.ligneerabstat), path('spark', views.kpitest), … -
Autofill Django model fields when create instance of another model
I have three models Student, Question and StudentAndQuestion class Student(models.Model): class Meta: verbose_name_plural = "Students" name = models.CharField(max_length=150) surname = models.CharField(max_length=150) code = models.CharField(max_length=10) # group = models.ForeignKey(Group,on_delete=models.CASCADE) points = models.IntegerField(default=0) class Question(models.Model): class Meta: verbose_name_plural = "Questions" text = models.CharField(max_length=1500) variants = models.CharField(max_length=1500) theme = models.OneToOneField(Theme, on_delete=models.CASCADE) anwser = models.CharField(max_length=1500) class StudentAndQuestion(models.Model): question = models.OneToOneField(Question,on_delete=models.CASCADE) student = models.OneToOneField(Student,on_delete=models.CASCADE) is_learned = models.BooleanField(default=0) points = models.IntegerField(default=0) I want Django make fill into StudentAndQuestion when i create new instance of students (for example create rows for all Questions and set points to zero) and when i create new instance of Question add it to all old students -
Using an existing sqlite3 database with django
I am getting started with Django and have this particular question regarding using my own SQLite database with Django. What I mean is that if I create a new database and populate it everything works fine. Here is my situation now. I have an existing database in my instance retail_data.sqlite3 in the BASE_DIR. I now want to use this as the data so I go ahed and add this to seettings as follows. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'retail_data':{ 'ENGINE':'django.db.backends.sqlite3', 'NAME':os.path.join(BASE_DIR,'retail_data.sqlite3') } } The above piece of code is replicated from this site. I then use the inspectdb command (python manage.py inspectdb --database=retail_data > salesapp/models.py) to generate the models.py which can use my current database. Also I go ahead and update the admin.py file so that I can see it from my admin panel. In the admin panel however even though the data table is visible I am unable to view the data. I was in doubt as to if the database actually consisted data so I used simple pandas.read_sql_query to query the data base and it has all the required data. How should I proceed? Your guidance is much needed. Thanks in advance -
Wagtail customizing admin
I am new to Wagtail and Django development. How can I change the colors of the admin page in Wagtail? According to some Q&A, I can change the colors through core.css but scanning through the code takes a lot of time. -
Why if I delete username field in django forms.ModelForm, registration fails?
I have a working example of a registration with username & email. I want to make it email only. When I start to manipulate it (ex. delete "username" in class UserForm (forms.py), I get IntegrityError at /application/register/ UNIQUE constraint failed: auth_user.username). How can I fix this? models.py class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # additional portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to="profile_pics", blank=True) def __str__(self): return self.user.username forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ("username", "email", "password") class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ("portfolio_site","profile_pic" ) views.py def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if "profile_pic" in request.FILES: profile.profile_pic = request.FILES["profile_pic"] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'application/register.html', { "user_form":user_form, "profile_form":profile_form, "registered":registered}) -
Django - Filter queryset after appending to it
I would like to filter a query set after I have added to it. See below view.py documents = Document.objects.all() for document in documents: document.hello = "Hello" # Lots more happens here like carrying out more querying and appending things on to document drawings = documents.filter(type='d') schedules = documents.filter(type='s') # Context.... render... etc.. template {% for document in drawings %} <p>{{document.hello}}</p> {% endfor %} {% for document in schedules %} <p>{{document.hello}}</p> {% endfor %} The problem I'm having is the information appended (like the 'Hello') are being lost when carrying out the filter. If I do the following all works fine. {% for document in documents %} <p>{{document.hello}}</p> {% endfor %} How do I transfer the appended information through the filter. Should I use a custom template filter instead of doing it in the view? Thanks -
Pyinstaller with Django: ModuleNotFoundError: No Module Named django.contrib.message.apps
I'm trying to run my packaged python application in the cmd line, and I get the error: ModuleNotFoundError: No Module Named 'django.contrib.message.apps' I used the answer from https://github.com/pyinstaller/pyinstaller/issues/2332 to get rid of the similar error for 'django.contrib.admin.apps', so does anyone know how to remove this one as well? -
how I can get all rows with booleanField equal to false?
I am trying to return all the rows with BooleanField equal true or false. I am using python django, the field name and field value store in dict: books = Book.objects.filter(**book_dict).prefetch_related(prefetch).select_related('book_pdf', 'book__pdf_file').distinct( 'id') the dict contain: {'fieldName__in': 'False'} and the actual query it always 'select ... where fieldName in (True)' I tryed to change the dict to: {'fieldName__in': 'false'} and got the same result, and also change to:{'fieldName__in': False} and got error: "bool is not iterable" -
Why I can't assign new permission to group in the same migration in Django
I'm trying to add new migrations by following this tutorial I added new permission inside Meta into permissions field. Then I created migration and tryed to modify this migration to update group permissions in place. But got DoesNotExist in RunPython operation. from django.db import migrations def assign_new_permission(apps, *args): Permission = apps.get_model('auth.Permission') Group = apps.get_model('auth.Group') # __fake__.DoesNotExist: Permission matching query does not exist. new_permission = Permission.objects.get( codename='my_new_permissoin_code') admins = Group.objects.get(name='Group name') admins.permissions.add(new_permission) class Migration(migrations.Migration): dependencies = [ ('my_app', '0066_some_migratoin'), ] operations = [ migrations.AlterModelOptions( name='my_model', options={'permissions': (('my_new_permissoin_code', 'Permission name'),)}, ), migrations.RunPython(assign_new_permission) ] -
Django: Why is my form sending POST data but returning request.method GET?
I expect the print(request.method) statement in my views.py to return POST below. I have seen other examples of code where request.method is POST. However my code simply outputs GET: test1 GET I can see that the form is sending POST data when I submit the info https://imgur.com/a/BSLLAgB After a bit of digging I found that HTTP is not designed to redirect POST data: https://softwareengineering.stackexchange.com/questions/99894/why-doesnt-http-have-post-redirect But leads me to ask why is my code redirecting this POST data? I would expect my views to return "POST" not "GET" because I'm not using a HttpResponseRedirect for example. Would like to understand why this happening and what I can do to stop Django redirecting that POST data to get GET. What am I missing? urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name = 'index'), path('add_coin/', views.add_coin, name = 'add_coin'), path('register/', views.register, name = 'register'), path('login/', views.user_login, name='login'), path('logout/', views.user_logout, name='logout') ] forms.py class PortfolioForm(forms.ModelForm): coin = forms.ModelChoiceField(queryset = Coin.objects.all()) amount = forms.IntegerField() trade_price = forms.DecimalField(decimal_places = 2) field_order = ['coin', 'amount', 'trade_price'] class Meta: model = Portfolio fields = {'coin', 'amount', 'trade_price', 'user'} exclude = ['user'] add_coin.html <form action="{% url index %)" method="post" name="add_coin"> <table> {{ … -
remove hostname of image link in django REST API
I have a model like below: # models.py # ================================================ def get_category_image_name(instance, filename): fn = os.path.join('img/thumbnailCategory/ct', str(instance.id) + '.png') return fn def get_food_t_image_name(instance, filename): fn = os.path.join('img/imgFood/ft', str(instance.id) + '.png') return fn def get_food_d_image_name(instance, filename): fn = os.path.join('img/DDD_Food/fd', str(instance.id) + '.png') return fn def id_generator(size=10, chars='123456789'): return ''.join(random.choice(chars) for _ in range(size)) class Category(models.Model): id = models.IntegerField(primary_key=True, unique=True, default=id_generator, editable=False) title = models.CharField(max_length=50, null=False, blank=False) c_thumbnail = models.ImageField(upload_to=get_category_image_name, null=False, blank=False) def save(self, *args, **kwargs): self.id = id_generator() super(Category, self).save(*args, **kwargs) def __str__(self): return '%s | %s' % (self.title, self.id) class Food(models.Model): food_id = models.IntegerField(primary_key=True, unique=True, default=id_generator, editable=False) name = models.CharField(max_length=30, null=False, blank=False) desc = models.TextField(max_length=200) category_id = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.IntegerField(null=False, blank=False) f_thumbnail = models.ImageField(upload_to=get_food_t_image_name) DDD_data = models.ImageField(upload_to=get_food_d_image_name) availability = models.BooleanField(default=True) discount = models.IntegerField(default=0) def save(self, *args, **kwargs): self.id = id_generator() super(Food, self).save(*args, **kwargs) def __str__(self): return '%s %s %s' % (self.name, self.category_id, self.price) I write a filter for foods that filter foods by category. My views.py is like: class GetListOfFoodsByCategory(viewsets.ModelViewSet): queryset = Food.objects.all() serializer_class = FoodSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('category_id',) And my urls.py has: router = routers.SimpleRouter() router.register(r'food', views.GetListOfFoodsByCategory) urlpatterns += router.urls And my serializer simply is like: class FoodSerializer(serializers.ModelSerializer): class Meta: model = Food fields … -
Ignore external sources being compressed in mezzinine
Tring to load external source in contact form template, mezzanine Example <script src="https://www.google.com/recaptcha/api.js" async defer></script> Compressor exception compressor.exceptions.UncompressableFileError: 'https://www.google.com/recaptcha/api.js' isn't accessible via COMPRESS_URL ('/static/') and can't be compressed -
How to return all images of a model in django REST
I have a model like below: # models.py # ========================================================================= class Food(models.Model): food_id = models.IntegerField(primary_key=True, unique=True) name = models.CharField(max_length=30, null=False, blank=False) desc = models.TextField(max_length=200) price = models.IntegerField(null=False, blank=False) f_thumbnail = models.ImageField(upload_to='img/imgFood/') DDD_data = models.ImageField(upload_to='img/DDD_Food/') def __str__(self): return '%s %s' % (self.name, self.price) when a client sends a request for all files, I want to give it a list of all image files of the Food class to it. How can I figure it out?