Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I fix "ERROR: Command errored out with exit status 1:" when trying to install django-visits
I am trying to install django-visits, but anytime I run the "pip install django-visits" command, I get the following error: ERROR: Command errored out with exit status 1: command: 'c:\users\samuel\appdata\local\programs\python\python37\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Samuel\\AppData\\Local\\Temp\\pip-insta ll-8t2j3cs9\\distribute\\setup.py'"'"'; __file__='"'"'C:\\Users\\Samuel\\AppData\\Local\\Temp\\pip-install-8t2j3cs9\\distribute\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__fi le__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3c s9\distribute\pip-egg-info' cwd: C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\ Complete output (15 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\__init__.py", line 2, in <module> from setuptools.extension import Extension, Library File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\extension.py", line 5, in <module> from setuptools.dist import _get_unpatched File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\dist.py", line 7, in <module> from setuptools.command.install import install File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\command\__init__.py", line 8, in <module> from setuptools.command import install_scripts File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\command\install_scripts.py", line 3, in <module> from pkg_resources import Distribution, PathMetadata, ensure_directory File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\pkg_resources.py", line 1518, in <module> register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider) AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.``` How can I fix it? -
change image index using jQuery
I have a list of images rendered from Django as follows: <div class="gallery"> <div class="slider-info"> <span class= "pagenum"> <span class="range"> <span id="currentIndex" class="currentIndex"> 1 </span> - <span id="totalCount" class="totalCount"> {{ item.images_cars_trucks_set.all|length }} </span> </span> </span> </div> <!-- images --> <span class="result-image-act"> <span class="img-group"> {% for image in item.images_cars_trucks_set.all %} {% if image.car_images_exists %} {% if forloop.counter == 1 %} <img src="{{image.car_images.url}}" class="active" id="{{image.id}}"> {% else %} <img src="{{image.car_images.url}}" id="{{image.id}}" class=""> {% endif%} {% endif %} {% empty %} <img src="{% static 'towns/images/list_page/no_image_available.png' %}" class="active" id="{{image.id}}"> {% endfor %} </span> <!--slide images --> <div class="swipe-wrap"> <div class="swipe-wrap-lef"> <span class="move" > <div class="swipe-prev"> <p>&lt;</p> </div> </span> </div> <div class="swipe-wrap-rig"> <span class="move" > <div class="swipe-next"> <p>&gt;</p> </div> </span> </div> </div> </span> </div> I have a jQuery script to change the displayed image when mouse hover on specific one as follows: <script type="text/javascript"> $(document).ready(function(){ $('.thumb-nails img').each(function(){ $(this).mouseover(function(){ $(".thumb-nails img").removeClass('img-border active'); $(this).addClass('img-border active'); var current_img = $(this).attr('id'); var image_displayed = $(this).attr('src'); $(".result-image-act img.active").removeClass('active'); $(".result-image-act img[id="+current_img+"]").addClass('active'); $('.result-image-act img.active').attr('src', image_displayed); }); }); }); The question is: How can I add to the Jquery script to indicate the image index number. I though to add number 1 to the first image and then replace each image ID with … -
How to add a value to an existing model record with the use of Django Forms?
I'm trying to make a form that adds points to a user's account. This form chooses which user and it should add it based on the value added. I don't know what I did wrong. No hints in the terminal to show what I did wrong. I just doesn't submit. The only indication that I screwed up is it shows that !form.is_valid based on the error message that I set. Here is my forms.py: class addpointForm(forms.ModelForm): add_point_field = forms.IntegerField(widget=forms.NumberInput) class Meta: model = Points fields = ['user'] Here is my views.py: def pointform(request): if request.method=='POST': form = addpointForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user messages.success(request, 'Success! Points has been added!') instance.points += addpointForm.add_point_field instance.save() else: messages.error(request, 'Oh no! Points has an error!') form = addpointForm() return render (request,'users/addpoints.html',{'form':form}) I just some help to point me in the right direction. Any help is appreciated thank you. -
Two foreign keys, only one can be not null at a time
I have a database table with two foreign keys pointing to two different tables. The business logic requires an "either or" relationship; only one foreign key can be NOT NULL at any given time. Here are the four possible states the foreign keys can hold based on the business logic: NULL, NULL - okay number, NULL - okay NULL, number - okay number, number - invalid business logic I'm using Django, and I know I can write some onSave() checks that will handle this, but that feels hackish. Is there a better method to deal with this business logic? -
Django AUTH_USER_MODEL refers to model '%s' that has not been installed
I've got the following models: from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.conf import settings class User(AbstractUser): username = models.CharField(blank=True, null=True) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] def __str__(self): return "{}".format(self.email) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') dob = models.DateField() phone = models.CharField(max_length=15) active = models.BooleanField(default=True) receive_newsletter = models.BooleanField(default=False, blank=True) So I have overwritten the default AUTH_USER_MODEL in settings.py to be: AUTH_USER_MODEL = 'myapp.User' but I'm getting the following error when running migrations: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'kofiapi.User' that has not been installed My project's structure is as follows: myapp api users - models.py myproject settings.py I have tried the following variations yet all failed: AUTH_USER_MODEL = 'myapp.api.users.User' AUTH_USER_MODEL = 'myapp.users.User' AUTH_USER_MODEL = 'myapp.api.User' AUTH_USER_MODEL = 'myapp.User' Any indication of what am I doing wrong? -
After updating the post, I want the user to be redirected to the post (Django - Python)
I want the user to be able to update existing posts. When the user clicks Update, then Post, they get an error message saying there is no URL to direct to. But the post does get updated on the backend. I thought the line return reverse('article_detail', kwargs={'slug': self.slug}) would redirect them back to their original post. class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now()) author = models.ForeignKey(User, on_delete=models.CASCADE) url= models.SlugField(max_length=500, blank=True) #url= models.SlugField(max_length=500, unique=True, blank=True) def save(self, *args, **kwargs): self.url= slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) Here is the table schema. sqlite> .schema blog_post CREATE TABLE IF NOT EXISTS "blog_post" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(100) NOT NULL, "content" text NOT NULL, "url" varchar(500) NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED, "date_posted" datetime NOT NULL); CREATE INDEX "blog_post_url_5af1045a" ON "blog_post" ("url"); CREATE INDEX "blog_post_author_id_dd7a8485" ON "blog_post" ("author_id"); sqlite> -
what i need to do for loading static
Hey everybody i have a problem with this code which i try to run on local host server , in this situation im followin an online project over youtube and he is trying to make an online resume, at the start we tried to make a simple home template which i stock in it so if u can help me to fix the problem in which cause to rise this error 'Static' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz and this the code itself: {% load Static %} <link href="{% static '/css/main.css' %}" rel= "stylesheet" type="text/css"> <h3> Hello world! <h3> <img src="{% static 'images/me.profile.jpg'%}" this is the setting.py by the way: STATIC_URL = '/static/' MEDIA_URL = '/Images/' STATIC_DIRS= [ os.path.join(BASE_DIR, 'static') ] -
I'm pulling a dictionary from an API call, when I pull URL information it quotes and brackets around them
I'm sure this will be an easy one for you guys, but I can't figure it out. I'm pulling the website information using a call in my Django template. All the information is getting pulled, but when I pull the website it has quotes and brackets around it like '[https://xxxxx.org]' obviously when I create the {{ web.site }} tag around it, it can't browse to the site. Is there a quick way to strip off all the extra '[]' around the URL? -
What is the most efficient way to make Post previews on Django?
I am making a Blog where I want for the home page to show only the first 100 characters of each post. My point is to make better use of space. If a person want to read a post, that person can just click to read it. I have some ideas on how to do it, but I think they won`t work or are inefficient: To create a subclass on blog models.py where I would inherit the Post class, save the first hundred characters of each content to a list and make a loop to save each list on the database; To place a instruction on blog views.py 'FirstPageView' class where it would only exhibit the first hundred characters. The 'Post' and 'FirstPageView' mentioned classes are as follows: on 'blog/views.py': from django.views.generic import ListView class FirstPageView(ListView): model = Post template_name = 'Blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 6 on 'blog/models.py': from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, models.SET_NULL, blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) So what would be … -
Do I have to use Redux with React for authentication?
This may be a stupid question. So, I am using Django for my backend and React for my frontend. The goal is to only show the objects that belong to the user that is making the request. Since Django takes care of authentication, do I need to use Redux, or any other framework for that matter, for authentication? Couldn't I just do something like: request.user.something.objects.all() on my backend when I receive the Axios request from my frontend? Do Axios request even provide the user? -
Can id field in django models be the same with two app instances running?
I don't understand well, how does django's autofield work... If I will run two app instances using gunicorn, will it be possible that my models get same autofield id? I have a model Message and I want to check it's instance's id, but I want to be absolutly sure, that the ids are unique and are going by adding order. -
How to store images like Images API
Hi this my model for create simple member already searched for several places and until now I haven't figured out how I can store the directory of my image next to my image field. class Member(models.Model): with open(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/api/data/states.json') as s: states_json = json.load(s) STATES = [(str(state["nome"]), str(state["sigla"])) for state in states_json] name = models.CharField(max_length=100, null=True, blank=True, verbose_name='Nome') image = models.ForeignKey( "wagtailimages.Image", blank=False, null=True, related_name="+", on_delete=models.SET_NULL, verbose_name='Imagem do membro', ) role = models.CharField(max_length=35, null=True, blank=True, verbose_name='Cargo') city = models.CharField(max_length=30, null=True, blank=True, verbose_name='Cidade') state = models.CharField( verbose_name='Estado', max_length=19, choices=STATES, default=('SP'), ) created = models.DateField(default=timezone.now, verbose_name='Atualizado') modified = models.DateField(default=timezone.now, verbose_name='Modificado') panels = [ FieldPanel("name"), ImageChooserPanel("image"), FieldPanel("role"), FieldPanel("city"), FieldPanel("state"), FieldPanel("created"), FieldPanel("modified"), ] def __str__(self): return self.name class Meta: verbose_name = 'Membro' verbose_name_plural = 'Membros' This work normally but how to store image informations like Wagtail Images API? Example: "detail_url": "http://localhost/api/v2/images/2/", "download_url": "/media/original_images/l8GlI3V.jpg" This my JSON from API [ { "id": 6, "name": "Gabriel", "role": "Desenvolvedor", "image": 4, "city": "Itapetininga", "state": "São Paulo", "created": "2020-04-26", "modified": "2020-04-26" } ] Thanks for help!!! -
Django project "pip install -r requirements.txt" error
I have a requirements.txt that looks like this: appdirs==1.4.3 asn1crypto==1.1.0 astroid==2.3.1 attrs==19.2.0 black==19.3b0 cffi==1.12.3 Click==7.0 colorama==0.4.1 cryptography==2.7 dj-database-url==0.5.0 Django==3.0.4 django-heroku==0.3.1 django-rest-knox==4.1.0 djangorestframework==3.10.3 gunicorn==19.9.0 isort==4.3.21 lazy-object-proxy==1.4.2 mccabe==0.6.1 psycopg2==2.8.3 pycparser==2.19 pylint==2.4.2 pytz==2019.3 six==1.12.0 sqlparse==0.3.0 toml==0.10.0 typed-ast==1.4.0 whitenoise==4.1.4 wrapt==1.11.2 I tried to install the requirements after I activated my virtualenv, but it gave me this error I noticed that at the end, it's saying "Microsoft Visual C++ 14.0 is required". Do I need to install Visual C++ or what's the solution here? -
Django: KeyError at / 'slug'
I'm trying to redirect user to a post according to the slug value. I'm using django-autoslug to populate the slug automatically based on the title. I'm trying to capture the slug value in sl variable however I'm getting KeyError at / 'slug' error.urls.py urlpatterns = [ path('', views.index), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] models.py from django.db import models from django.template.defaultfilters import slugify from autoslug import AutoSlugField class express_publish(models.Model): title=models.CharField(max_length=200) slug = AutoSlugField(populate_from='title',unique=True) author=models.CharField(max_length=50) body=models.TextField() time=models.DateTimeField(auto_now_add=True) def __str__(self): return self.title views.py from django.shortcuts import render,redirect from django.views import generic from .models import * from .forms import * def index(request): all_publish=express_publish.objects.all() form=express_publishForm() if request.method=="POST": form=express_publishForm(request.POST) if form.is_valid(): form.save() sl=form.cleaned_data['slug'] return redirect('/'+sl) context={'all_publish':all_publish,'form':form} return render(request,'publish/index.html',context) class PostDetail(generic.DetailView): model = express_publish template_name = 'publish/post_detail.html' -
Django: saving a User in ManyToManyField
What I am trying to do is to allow the authenticated users to give a like to an article. models.py: class NewsItem(models.Model): heading = models.CharField(max_length=550, blank = False) news_body = models.TextField(blank = True) ... likes = models.ManyToManyField(User, blank = True) views.py: def newsitem_slug(request, newsitem_id, slug): newsitem = get_object_or_404(NewsItem, pk=newsitem_id, active = 1) ... # Processing Likes: if request.method == 'POST' and request.POST.get('newsitem_like'): form = LikesForm(request.POST, instance=newsitem) if form.is_valid(): user = User(id=request.user.id) if user not in newsitem.likes.all(): newsitem.likes.add(user) else: newsitem.likes.remove(user) ... forms.py: class LikesForm(ModelForm): class Meta: model = NewsItem fields = ['likes',] I get an error when adding a like: Cannot add "<User: >": instance is on database "default", value is on database "None" It is recommended to save both a user and an article before using the add method, but it does not seem to be working in my case. What can be done about that? -
How to use class which defined below in Python 3.6?
I need to request class "Product" in class "Collection" below to create a Many-to-Many connection. But the compiler says that the name "Product" is not defined. Are there any possible ways to do it? class Collection(models.Model): products = models.ManyToManyField(Product, blank=True, on_delete=models.CASCADE) class Product(models.Model): collection = models.ManyToManyField(Collection, blank=True, on_delete=models.CASCADE) I just need to put "Product" in "Collection" and vice versa. -
Django queryset with regex returning blank
I made a feature that can call user using @(at sign) and user's nickname. At commentbox, I can use @stackoverflow to notify user's nickanem called stackoverflow. This is part of my code. views.py import re at_sign_object = FreeBoardComment.objects.filter(comment_writer=request.user).order_by("-pk")[0] at_sign = str(at_sign_object) get_nickname = re.findall(r"@([0-9a-zA-Z가-힣]+)", at_sign) print(get_nickname) When user put @ sign and nickname of other user, it successfully prints the nickname of other user. But the problem is, I'm trying to send a notification to that user. So I made a queryset that finds user with their nickname. find_user = CustomUser.objects.filter(nickname=get_nickname) print(find_user) But this code is keep printing blank queryset result like this: I can't understand why my code is not working because I also tried doing this in django shell. like this >>> from users.models import CustomUser >>> find_user = CustomUser.objects.get(nickname="admin") >>> print(find_user) admin -
What are the problems of having two Django projects sharing the same database?
I am building a system that has two components, one is a Web application powered by Django 2.2 and other is a worker that does background processing (its work is not started by the Web app). Both components need to communicate to each other in a bi-directional way. They will use the same database (there is no need to make them independent), inclusive handling the same tables. From Django the Worker will use only the ORM modules, it will own tables that are not known by the Web app (and vice versa). So I will need to run migrations in both components that targets the same database. Are there problems? or for Django that components are seem as two Django apps that use the same database? -
Nginx and gunicron serve django app and media files on the same port
I have a remote server used to serve a django application. when I choose DEBUG=False I had to add a nginx server to serve media files from /media folder. when I try to restart nginx after running gunicron I get an error saying that port 8000 is used. how do I manage to serve the app and the media files on the same port? This is the actual content of mysite_nginx.conf file server { listen 8000; listen [::]:80; ... location / { proxy_pass "http://localhost:8000"; } } -
How fix this error in mysqlclient installation Django?
Command "C:\Users\ASUS\PycharmProjects\FirstSite\venv\Scripts\python.exe -u -c "import setuptools, tokenize;file='C:\Users\ASUS\AppData\Local\Temp\pip-install-fodye6z3\mysqlcl ient\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\ASUS\AppData\Lo cal\Temp\pip-record-awzk5j0l\install-record.txt --single-version-externally-managed --compile --install-headers C:\Users\ASUS\PycharmProjects\FirstSite\venv\include\site\python3.8\mysqlc lient" failed with error code 1 in C:\Users\ASUS\AppData\Local\Temp\pip-install-fodye6z3\mysqlclient\ -
How to get object_set in serializer from Many to Many?
I want to allow saving some specific field only if it responds to some statement. Let me explain. models.py class classe(models.Model): name = models.CharField(max_length=191) groups = models.ManyToManyField('Group') persons = models.ManyToManyField('Person') class Group(models.Model): name = models.CharField(max_length=191) persons = models.ManyToManyField('Person') class Person: name = models.CharField(max_length=191) serializers.py class GroupSerializer(serializers.ModelSerializer): persons = PersonSerializer(many=True, read_only=True) person_id = serializers.PrimaryKeyRekatedField(queryset=Person.objects.all(), write_only=True) def update(self, instance, validated_data, **kwargs): instance.name = validated_data.get('name', instance.name) person_field = validated_data.get('person_id) classe = instance.classe_set #This one doesn't work person_classe = classe.persons.all() #This one too if (person_field in person_classe): instance.persons.add(person_field) instance.save() return instance So, the person_field can be saved only if the person is in the actual classe. Everything work fine, but the two commented lines don't, so can't access the if statement. Does someone know how can I figure it out ? -
Django static files is working but media is not
I dont understand why my media files is not displaying like my static files. My question is very similar to Django media not loading, static files working because i am also using django-oscar but the answer is not working for me. base.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # MEDIA_ROOT = r'C:\Users\Michal\django-react-boilerplate\home\media' STATIC_URL = '/static/' print(STATIC_ROOT) print(MEDIA_ROOT) result of prints C:\Users\Michal\django-react-boilerplate\home\static C:\Users\Michal\django-react-boilerplate\home\media both folders have same files but if i type 127.0.0.1:8000/static/fashion.jpg/ it return image. 127.0.0.1:8000/static/media.jpg/ return error 500 template does not exist. Adding full path image to MEDIA_ROOT is not helping. -
Django KeyError at /admin Exception Value: 'actions'
Learning Django by this book, charter 6 ---- https://github.com/PacktPublishing/Django-2-by-Example Using PyCharm Community After add signalscannot open some urls in admin, see error like "KeyError at /admin/account/profile/" or "KeyError at /admin/images/image/" enter image description here enter image description here I think it becouse pycharm don't find decorators files (common) and action files. But I create in project "common' folder with decorators.py and empty init.py And "action" folder with models.py, utils.py was added. How I can fixed it, can you say me, please? p.s. actions.utils and actions.models was red underline too, i try select "ignore this" in pycharm -
Django Sqlite model class has no attibute objects
I hope you all are in good health. I am newbie working on Django. Currently I am need to retrieve items from the SQLite database and display it on the html through Django back-end. Spend alot time on stack-overflow their are similar questions but didn't find any help View.py from django.shortcuts import render from django.http import HttpResponse from .models import mizoso_table def home(request): context = { "post" : mizoso_table.objects.all() } return render(request,'mizoso/home.html',context=context) def product(request): return render(request,'mizoso/products.html') Models.py from django.db import models import datetime from django.contrib.auth.models import User # Create your models here. class mizoso_table(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title models and views class is located in the same folder. I tried it on the shell. Its working fine their. I will be very thankful if someone would help me in finding the bug. Thank you! Shell Picture: -
How to modify Django template variable with JS and return it changes on it
I would like to pass a list of ids to a view when i click on a link: <a href="{% url 'app:manage_ids' %}?ids={{ids}}"> So i have created a template var and pass it to js: {% with ids="" %} <script type="text/javascript"> window.ids = "{{ ids }}"; </script> {% endwith %} I manage object ids when click on checkbox, adding or removing it to a list: $('.checkbox').change(function() { var id = $(this).val(); // if django template var is empty var list_ids = []; // else var list_ids = window.ids; if ($(this).is(':checked')) { list_ids.push(id); // here i have to save it on a django template var to use it on the click link } else { const index = list_ids.indexOf(id); if (index > -1) { list_ids.splice(index, 1); // here i have to save it on a django template var to use it on the click link } } }); Anybody could help me about how to do it ? Thanks you so much.