Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Facing problem in installing mysqlclient in python
I am a beginner in python. I am doing my college project in django-python. I want to use MySQL (phpMyAdmin). I am facing problem in installing mysqlclient. The error is given below... C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,3,12,'final',0) -D__version__=1.3.12 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include" -Ic:\users\bhuvan_02\appdata\local\programs\python\python37\include -Ic:\users\bhuvan_02\appdata\local\programs\python\python37\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.15.26726\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\cppwinrt" /Tc_mysql.c /Fobuild\temp.win-amd64-3.7\Release_mysql.obj /Zl _mysql.c _mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\cl.exe' failed with exit status 2 -
Django get average (string)
Models.py class Mood(models.Model): moods=models.CharField(max_length=500) image = models.ImageField(upload_to='moods/', blank=True, null=True) count=models.IntegerField(blank=True,null=True,default=0) def __str__(self): return str(self.moods) class UserMood(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) mood=models.ForeignKey(Mood,on_delete=models.CASCADE) def __str__(self): return str(self.id) views.py user_moods=UserMood.objects.filter(user=request.user) user_stats['average_mood']='' need to get average mode based on UserMood entries. -
How to force download files through pafy and youtube-dl in Dhango webapp
I have made a youtube video downloader app with django and pafy. The problem in the final link which I am getting is something like https://r5---sn-gwpa-jj0z-blah-blah. These links are opening files in the browser how to make them downloadable on clients machine? The Template I am using to get the download link is, {% for resolution,extension,file_size,url in streams %} <tr> <td>{{ resolution }}</td> <td>{{ file_size }}</td> <td>{{ extension }}</td> <td><a href="{{ url }}" download="{{ title }}.{{ extension }}" type="application/octet-stream" ><span class="glyphicon glyphicon-download-alt" ></span> Download</a></td> </tr> {% endfor %} Is it possible to get the direct links from youtube-dl, I did a lot of searching but didn't found a valid answer nothing worked for me? -
Full crud log information save in django_admin_log table in Django 2
I'm new in Django. I'm working on a project where I need every user action (CRUD) will be log down in django_admin_log table. I try a few searches but not properly log down every information. -
Save a many to many object inside a django model?
I am still learning to use Django and so I am a bit unclear on something.I have a product model and category model. A product can lie in multiple categories and multiple categories can have the same product. So, its a many to many relationship. Now, I want to allow the user to select multiple categories from the html and then I want to save the categories and link them to the category object in my product model. I am completely lost about it. One way would be to use Modelform but I dont want to go that way. Is there any other way I can accomplish this? models.py class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for product page URL, created from name.') description = models.TextField() is_active = models.BooleanField(default=True) meta_keywords = models.CharField("Meta Keywords", max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag') meta_description = models.CharField("Meta Description", max_length=255, help_text='Content for description meta tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('catalog:categories', kwargs={'category_slug': self.slug}) class Meta: ordering = ['-created_at'] verbose_name_plural = 'Categories' class Product(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True, help_text='Unique value for product page URL, created from name.') brand … -
Django defining default database for a model without assigning a database router?
In my django project I have a lot of models. For analytics I have implemented an app which is write intense and also the data use a secondary database. The app is working well with the database router and also the manual method as I configured as per the docs. My Issue is that whenever I query another models outside of analytics app, DatabaseRouter is called for each and every request. So I choose to go with the manual method. So for every query I had to use .using('analytics') for every query. I would like to configure the database in the model manager. These are the methods I tried, but I couldn't get it to work. (The manager is a base class of BaseManager instance which is base class of a Queryset, which is where the using method is defined.) Model Attribute class UserVisit(models.Model): # fields @property def objects(self): return self.objects.using('analytics') Manager class VisitManager(models.Manager): def __init__(self): super(VisitManager, self).__init__() self.using('analytics') class UserVisit(models.Model): objects = VisitManager() Setting db with shell works. UserVisit.objects.all() <QuerySet []> UserVisit.objects._db='analytics' UserVisit.objects. # this works. making the above change on a manager doesn't work class VisitManager(models.Manager): def __init__(self): super(VisitManager, self).__init__() self._db = 'analytics' class UserVisit(models.Model): objects = VisitManager() … -
add foreig key (user) value in fields of createview django
I want to insert data and I am using create view. The problem is I also want to pass a foreign key in a field which is not coming from form how to do it? example: class Addfile(CreateView): model=uploadAssignment fields=['teacher','title','description','deadline'] All the fields except teacher are coming from a form.Whereas the teacher will the be user object who is logged in, how to save it in a fields(teacher)? -
Html include tag from Model property instance
I am attempting to render: Histogram saved as a png image Folium map from a html file I have successfully rendered the histogram, but am failing to render the Folium map. Instead, results.html is loading with NONE where I am expecting the Folium map to be. I am unsure whether it is possible to use HTML include tag for a property instance method? Models.py class Hashtag(models.Model): def display_locations(self): """ Function to create a dict by frequency of the locations associated with search_text """ country_list = list(self.location.values_list('country', flat=True).all()) for country in country_list: location_freq = {i:country_list.count(i) for i in set(country_list)} return location_freq @property def get_histogram(self): """ Function to create and save histogram of Hashtag.locations """ location_freq = self.display_locations() plt.bar(list(location_freq.keys()), location_freq.values(), color='g') plt.show() plt.savefig('mapping_twitter/static/mapping_twitter/images/histogram/histogram.png') @property def get_heatmap(self): """ Function to create and save heatmap of Hashtag.locations """ location_map = folium.Map( location=[51.5074, 0.1278], tiles="Stamen Terrain", zoom_start=12) location_map.save('mapping_twitter/templates/mapping_twitter/heatmap.html') Results.html <h3>Histogram</h3> <div class="boxed"> <p> {{ hashtag.get_histogram }} <img src="{% static 'mapping_twitter/images/histogram/histogram.png' %}" /> </p> </div> <h3>Heatmap</h3> <div class="boxed"> <p> {{ hashtag.get_heatmap }} {% include 'mapping_twitter/heatmap.html' %} </p> </div> -
Add object to ManyToMany field using CreateModelMixin.create()
I use mixins.CreateModelMixin.create to create object, but also I need to add request.user to m2m fields in it. So my idea is to catch the object from self.create() and than filally make obj.users.add(user). But CreateModelMixin return only responce. How can I get an object from .create? Is it a better way to add user? Can I user super (not good in it)? Thanks! -
Django admin default direction of sorting
When I click on table header in django admin it sorts data in ASC direction first. How can I change this default direction for some of columns? -
Serializers - Django REST framework (AttributeError: Got AttributeError when attempting to get a value for field `user` on serializer)
AttributeError: Got AttributeError when attempting to get a value for field user on serializer UserKeywordSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. models.py class Keyword(models.Model): name=models.CharField(max_length=500,unique=True) image = models.ImageField(upload_to='keywords/', blank=True, null=True) mood=models.ManyToManyField(Mood,blank=True) def __str__(self): return str(self.name) class UserKeyword(models.Model): keywords=models.ManyToManyField(Keyword) count=models.IntegerField(blank=True,null=True,default=0) user=models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return str(self.id) serializer.py class KeywordsSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields ='__all__' class UserKeywordSerializer(serializers.ModelSerializer): keywords = KeywordsSerializer( read_only=True,many=True) class Meta: model = UserKeyword fields = '__all__' views.py top_keywords=UserKeyword.objects.filter(user_id=request.user.id).select_related().order_by('-count') user_serializer=UserKeywordSerializer(top_keywords).data print(user_serializer) -
After deleting digitalocean spaces static link still point to digitalocean
I deleted my whole digitalocean spaces since I want to switch to Amazon S3. After finish all the settings of django with Amazon S3,I deleted digitalocean spaces and run python manage.py collectstatic all the static files have been uploaded into AWS S3,and I run sudo systemctl restart nginx to restart nginx. But when I console the browser.I found all the static url still pointed to digitalocean spaces but not AWS S3. -
Using Django-taggit and django-taggit-serializer, aren't able to save tags
I am trying to add tags in my model by taggit and taggit serializer. I making my API in rest framework. I followed the instruction(https://github.com/glemmaPaul/django-taggit-serializer) but it is still an issues: "tags": [ "Invalid json list. A tag list submitted in string form must be valid json." /setting.py INSTALLED_APPS = [ [...] 'rest_framework', 'taggit', 'taggit_serializer', ] /models.py tags = TaggableManager(blank = True) /serializer.py class JobSerializer(TaggitSerializer,serializers.HyperlinkedModelSerializer): # tag serializer tags = TagListSerializerField() There is noting changed in the view.py. thanks in advanced, -
Django allow return response before another proccess finished
I have a problem when I want to run a webhook. In this case I want to run another script to build the project, let say runaway.sh #!/bin/bash cd /home/myuser/envs/titipbeliin-vue git pull https://username:password@gitlab.com/username/project-vue npm install npm run build and then in my views.py, I try to call it command: @csrf_exempt def gitlab_webhook_view(request): header_signature = request.META.get('HTTP_X_GITLAB_TOKEN') if header_signature == settings.GITLAB_WEBHOOK_KEY: subprocess.call(os.path.join(settings.BASE_DIR, 'runaway.sh')) return HttpResponse('pull & build welldone!') return HttpResponseForbidden('Permission denied.') But gitlab always return Hook execution failed: Net::ReadTimeout, As we know npm install & npm run build take a long time. So, I want to continuing that process in the background service, and for a few seconds just return "pull & build welldone!". Thank before.. -
What is the difference between Django and Flask in using filter?
Hi friends all around the world ,There is a problem which is perplexing me for days .When I used Django I used obj=User.objects.filter(uname=username,pwd=password) the User is a class to migrate to Mysql But when I used Flask obj = User.query.filter(User.uname == username, User.pwd == password).first() I need to do this to realize login .I think there is somethings different between Django and Flask .I know the "=" is assigning operator and the "==" is relational operator .It's appreciate that you can help me , Thank you ! -
Retrieving users password from Django and passing as variable to log in to Django REST
I have a Django powered web-app which also utilizes the Django REST framework. I want to read and write to my database using the API generated by Django REST. I can do this successfully when I hardcode the password of the current user, but I can't do this when I attempt to pass in the retrieved password from Django, as Django does not store the password as plain text. (I know I can change this, but I am hoping there is a better way). Essentially, my logic flow is this: user logs in using Django login form user would like to write new data to database, but will need API token Obtain API token (already generated when they sign up) use this token to authenticate and POST JSON data to REST framework I can do all of these steps above when I hardcode the password as plain text in my script, but I would like to "retrieve" the password and pass it automatically if possible. Code below works as described above: views.py class DefaultsListView(LoginRequiredMixin,ListView): model = models.DefaultDMLSProcessParams template_name = 'defaults_list.html' login_url = 'login' def get_queryset(self): return models.DefaultDMLSProcessParams.objects.filter (customerTag=self.request.user.customerTag) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) testing = super().get_context_data(**kwargs) userName = str(self.request.user.username) … -
create() takes 1 positional argument but 3 were given
It's my first time creating an api rest with django rest framework, I got to the point of Register users and log them with token, my problem is that all this I could do with the default user of Django, in my case I need a personalized user that has another boolean variable called is_technical (is_technical). I will put the relevant code that I made so far but to be clear, I want to make a login system with DRF and One-To-One Link... models.py (i tried override several times the create method but it doesnt work) class Usuario(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) es_tecnico = models.BooleanField(name = 'es_tecnico', default = False, blank = True) views.py class UsuarioViewSet(viewsets.ModelViewSet): lookup_field = 'id' serializer_class = UsuarioSerializer queryset = Usuario.objects.all().filter(es_tecnico = False) class TecnicoViewSet(viewsets.ModelViewSet): lookup_field = 'id' serializer_class = UsuarioSerializer queryset = Usuario.objects.all().filter(es_tecnico = True) class PedidoViewSet(viewsets.ModelViewSet): lookup_field = 'id' serializer_class = PedidoSerializer queryset = Pedido.objects.all() # class PedidoMiUsuarioSet(viewsets.ModelViewSet): # serializer_class = PedidoSerializer # queryset = Pedido.objects.all().order_by('-id').filter(autor = "3") class Registrar(mixins.CreateModelMixin, viewsets.GenericViewSet): serializer_class = UsuarioSerializer def create(self, request, *args, **kwargs): # Creando un nuevo usuario username = request.POST.get('user.username') password = request.POST.get('user.password') es_tecnico = request.POST.get('user.es_tecnico') print(username) user = User.objects.create_user(username, password) user.save() token = Token.objects.create(user=user) … -
Django clean is running on a non-required field
I have a non-required field in my form called into_alias. When form.valid() is called in my view, it is trying to run clean_into_alias to validate this field. However, when no value for the field is provided it is still trying clean it and I get this error: DoesNotExist at /department/b6c1f70de01d488faac5247f54414b5f/merge/delete {'name_short': ''} forms.py class DeptMergeDeleteForm(forms.Form): def init(self, *args, **kwargs): self.department = kwargs.pop('department', None) super(DeptMergeDeleteForm, self).init(*args, **kwargs) into_alias = forms.CharField( required = False, max_length = 51, label = mark_safe("""When you delete this department, do you want to merge its members into another department? If so, please provide the alias of the department that you want to merge these employees into "e.g. @tech_support")"""), validators=[valid_dept_alias_chars, valid_dept_alias_exists,], ) def clean_into_alias(self): dept_drop = self.department data = self.cleaned_data['into_alias'] dept_into = Department.nodes.get(name_short=data) #<------- ERROR if dept_into == dept_drop: raise ValidationError("You cannot merge your members into the same department that you are about to drop ;)") # return the cleaned data return data Maybe {'name_short': ''} is an empty string, not None? -
Ordering Django querysets using a JSONField's properties
I have a model that kinda looks like this: class Person(models.Model): data = JSONField() The data field has 2 properties, name, and age. Now, lets say I want to get a paginated queryset (each page containing 20 people), with a filter where age is greater than 25, and the queryset is to be ordered in descending order. In a usual setup, that is, a normalized database, I can write this query like so: person_list_page_1 = Person.objects.filter(age > 25).order_by('-age')[:20] Now, what is the equivalence of the above when filtering and ordering using keys stored in the JSONField? I have researched into this, and it seems it was meant to be a feature for 2.1, but I can't seem to find anything relevant. Link to the ticket about it being implemented in the future I also have another question. Lets say we filter and order using the JSONField. Will the ORM have to get all the objects, filter, and order them before sending the first 20 in such a case? That is, will performance be legitimately slower? Obviously, I know a normalized database is far better for these things, but my hands are kinda tied. -
Error when field is left empty: invalid literal for int() with base 10
I am saving a new article in the database. Here is a simplified script that I use: class Article(models.Model): name = models.CharField(max_length=255) rating = models.PositiveSmallIntegerField(blank=True, null=True) Then here is how I try to create a new record: article = Article( name = request.POST['name'], rating = request.POST['rating'], ) article.save() The problem, however, is that the rating is not always set. The field can be null, so that is no problem. However, at the moment if the field is left empty, it returns an error: invalid literal for int() with base 10. I would like to basically say: If POST['rating'] is set, then use that If not, then the field should be null. I'm new to Python and not sure how to achieve this. -
How to do source envvars before running apache
Is there a way to do source credentials before running a django project from apache? My file looks like: export DB_USERNAME=root export DB_HOST=xx.yy.ss.dd Or, do I have to put everything in my wsgi.py file? -
How to update a django QuerySet where the fields need to be different values
I have a queryset, and I need to update two fields by incrementing a number in the fields. So, I have: cycles = Cycle.objects.filter(cycle_id='D4_w1'), and I need to update these fields to D5_w1, which is easy enough using cycles.update(cycle_id='D5_w1'), but I also need to update the value of another field, whose string is different for each entry. So, event.cycle_event='D4_w1_some_string' where some_string is different for every item in the queryset. One of my issues is that event.cycle_event is coming from my Event model. Fortunately, the Events with cycle_event='D5_w1_some_string' already exist, but I am having trouble updating the event field in Cycle to match the new object. I've tried updating them all individually by iterating through the queryset: for c in cycles: e = c.event.cycle_event e = e.replace('D4_w1', 'D5_w1') event = Event.objects.get(cycle_event=e) c.event = event c.save() But I believe django prevents you from modifying entries this way, because it only saves it to the instance c, rather than saving it to the database when I do it this way. What else should I try? -
invalid literal for int() with base 10: 'create'
I have model: class Article(models.Model): id = models.AutoField(primary_key=True) title=models.CharField(max_length=30); description=models.TextField(); date=models.DateTimeField(auto_now_add=True); author = models.ForeignKey(User, null=True, blank=True, on_delete=models.PROTECT) def __str__(self): return self.title; def snipped(self): return self.description[:50]+'...' I have form: class CreateArticle(forms.ModelForm): class Meta: model=models.Article fields=['title','description'] And View.py class ArticleCreateView(CreateView): template_name = 'articles/article_create.html'; form_class = CreateArticle; queryset = Article.objects.all() def form_valid(self, form): instance = form.save(commit=True) instance.author = forms.user instance.save() Two qwestions: 1)Error invalid literal for int() with base 10: 'create' 2) How get current user? -
Image not appearing in template in django 2.1
I am making a profile page for my website. I have followed a couple peoples instructions online and I did what they said (i.e. media_url, media_root, changes to my urls.py). I register my superuser through the admin page, and I give it a profile. When trying to get my image, it does not display. Here is my code: Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Pic = models.ImageField(default='default.png', blank=True, upload_to='img') address = models.CharField(max_length=70, default='Bensons', unique=True) email = models.EmailField(max_length=70, unique=True, default='ben@email.com') def __str__(self): return self.address settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=ytl^8!j@t(^c5eile%%x(l3hvkekc$z#_t538+%a)p2uvsr!+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['192.168.1.192'] STATIC_URL = '/static/' # Application definition INSTALLED_APPS = [ 'crispy_forms', 'index.apps.IndexConfig', 'django.contrib.admin', 'django.contrib.auth', #yoohoo 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'campaign.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, … -
Django-rest-framework Differents serializers
I have an api with django-rest-framework (last version) and I need different responses depending on the content-type asked. Right now, I expect application/vnd.api+json or text/html (for browsable api). But I need to add another response for application/vnd.oasis.stix+json; version=2.0. I tried to add a new custom renderer but it only allows me to specify "application/json". I know that I can send differents serializers, but I don't know how to discriminate different content-types.