Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Black Not Installing Properly
I received an error after installing Django Black. I ran "pipenv install black --pre". Then when I ran manage.py runserver, I received the error below. Note that I am running Windows 10. from custom_storages import MediaStorage File "C:\Users\dgold2\Documents\py\ibankai\src\custom_storages.py", line 2, in <module> from storages.backends.s3boto3 import S3Boto3Storage File "C:\Users\dgold2\Documents\py\ibankai\src\.venv\lib\site-packages\storages\backends\s3boto3.py", line 18, in <module> from django.utils.six.moves.urllib import parse as urlparse ModuleNotFoundError: No module named 'django.utils.six' -
Invalid URL. Django
I created search form: <form action="{% url 'search_results' %}" method="get"> <div class="row"> <div class="col-lg-8 col-md-6 col-xs-12"> <input name="q" type="text" placeholder="Search..." class="form-control"> </div> <div class="col-lg-3 col-md-6 col-xs-12"> <select name="q2" class="form-control" id="exampleFormControlSelect1"> <option>All locations</option> <option>Москва</option> <option>Петербург</option> <option>Казань</option> </select> </div> <div class="col-lg-1 col-md-6 col-xs-12"> <!-- <button> Search </button> --> <button class="btn btn-primary">Primary</button> </div> </div> </form> When I input "c++" I go to http://127.0.0.1:8001/search/?q=c%2B%2B&q2=%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0 (Result is OK, but '+' is interpreted as %2B) When I click pagination "next" I receive http://127.0.0.1:8001/search/?vacancy=2&q=c++&q2=%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0 (ERROR Page not found) I need http://127.0.0.1:8001/search/?vacancy=2&q=c%2B%2B&q2=%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0 How can I fix this (convert '+' to '%2B')? vacancy_list.html {% extends 'vacancy_list/base.html' %} {% block content %} <div class="container " style="margin:20px;"> <!-- wrapper for all containers --> <div class="container" style="margin-top: 40px; font-size: 2rem;"> <form action="{% url 'search_results' %}" method="get"> <div class="row"> <div class="col-lg-8 col-md-6 col-xs-12"> <input name="q" type="text" placeholder="Search..." class="form-control"> </div> <div class="col-lg-3 col-md-6 col-xs-12"> <select name="q2" class="form-control" id="exampleFormControlSelect1"> <option>All locations</option> <option>Москва</option> <option>Петербург</option> <option>Казань</option> </select> </div> <div class="col-lg-1 col-md-6 col-xs-12"> <!-- <button> Search </button> --> <button class="btn btn-primary">Primary</button> </div> </div> </form> </div> {% for vacancy in vacancies %} <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-8"> <h1><a href="{% url 'vacancy_detail' pk=vacancy.pk %}">{{vacancy.title}}</a></h1> </div> <div class="col-md-4 text-right"> <p> {{ vacancy.salary}} </p> </div> </div> </div> <div class="card-body" … -
Django CMS CSS trouble?
Im trying to style a plugin in my Django-CMS project ( django 1.11, CMS 3.6.0 ). Im trying to add my class to my plugin html, like this : <div class="question"> <h1 class="question-title">{{ instance.poll.question }}</h1> <form action="{% url 'polls:vote' instance.poll.id %}" method="post"> {% csrf_token %} <div class="form-group"> {% for choice in instance.poll.choice_set.all %} <div class="radio"> <label> <input type="radio" name="choice" value="{{ choice.id }}"> {{ choice.choice_text }} </label> </div> {% endfor %} </div> <input type="submit" value="Vote" /> </form> </div> Then I go into my css, and try to apply some styles to the plugin, but nothing happens. When I inspect my div which should have a class of "question" in the browser, there is no class even though I specified it in my html. Why is that ? When I do something like : body { width: 1060px; margin: 10px auto; } It applies the styles correctly. Anybody knows what is happening here ? Where are my custom classes from the html ? I was trying to find a guide on Django-CMS and styling, but Im not having much luck. Thank you guys ! -
Passing data from external python script in django to swift
Trying to create a swift request where an external python script is run in Django and returns data to the user. I just cant wrap my head around on what best practices there are or on how to do this. Any help would be appreciated. Python script returns print(output) Djano views.py def post(self, request, *args, **kwargs): self.create(request, *args, **kwargs) inp = request.FILES.get('image').name out = run([sys.executable,'//Users//macbookpro//TestAPI//venv//Test_Script.py',inp],shell=False,stdout=PIPE, text= True) print(out.stdout) return Response ({"output": str(out)}) Swift to: REST_UPLOAD_API_URL, headers: headers, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in debugPrint(response) print(stdout) What would be the best way to pass data from the Python script and back to the user? Do i need to create a JSON response in Django and afterwards Decode it in Swift? If so, how would that work? If not, then how can you decode the "stdout" response in Swift which I'm currently receiving. Results so far: print(out.stdout) gives me the desired text response within Django DebugPrint(response) = Returns desires text --> stdout='MyDesiredText\n')"; print(stdout) in Swift gives me = 0x000000010a45d1a8 -
Django file not uploading: ValueError at / The 'image' attribute has no file associated with it
I created a form with django forms. I implemendted on html page. Everything is ok but my image not uploaded on database. I was trying to find issue. I tried print(request.FILES) It returned <MultiValueDict: {}> I understood my uploaded image didn't upload correctly im my database. Though form was submitted and when I tryied to query from product it will get error ValueError at / The 'image' attribute has no file associated with it. this is my traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.5 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'product.apps.ProductConfig'] Installed 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'] Template error: In template /home/asad/PycharmProjects/eShop/templates/base.html, error at line 8 The 'image' attribute has no file associated with it. 1 : {% load staticfiles %} 2 : <!DOCTYPE html> 3 : <html lang="en"> 4 : <head> 5 : <meta charset="UTF-8"> 6 : <title>{% block title %}{% endblock %}</title> 7 : <!-- Latest compiled and minified CSS --> 8 : <link rel="stylesheet" href="https://maxcd n.bootstrapcdn.com/ bootstrap/4.3.1/css/bootstrap.min.css"> 9 : 10 : 11 : </head> 12 : <body> 13 : 14 : <div class="container"> 15 : <div class="row"> 16 : <div class="col-md-4"> 17 : <a … -
How to save foreign from html form (select)?
I can not save the appropriate value for ForeignKey from the form. The value of ForeignKey is always written to the database, with id = 1. in html form the values from my model, which is in the database, are output to the select. But when sending data from the form, the values of the fields for which the type of foregonekey are written to the database all the time by id = 1 models.py: class Sportsman(models.Model): first_name = models.CharField(max_length=64, blank=True, null=True, default=None, verbose_name='Имя') last_name = models.CharField(max_length=64, blank=True, null=True, default=None, verbose_name='Фамилия') gender = models.ForeignKey(Gender, on_delete=models.CASCADE, null=True, blank=True, default=True, verbose_name='Пол') tournament = models.ForeignKey(Tournament, null=True, blank=True, default=True, on_delete=models.CASCADE, verbose_name='Турнир') def __str__(self): return "Спортсмен(ка): %s %s, почта: %s" % (self.first_name, self.last_name, self.email) class Meta: verbose_name = 'Спортсмен' verbose_name_plural = 'Спортсмены' def save(self, *args, **kwargs): super(Sportsman, self).save(*args, **kwargs) forms.py: class SportsmenForm(forms.ModelForm): class Meta: model = Sportsman exclude = ['created', 'updated'] views.py: def sportsman(request): documents = Document.objects.filter(is_active=True) form = SportsmenForm(request.POST or None) if request.method == "POST" and form.is_valid(): print(request.POST) print(form.cleaned_data) print(form.cleaned_data['email']) form.save() new_form = form.save() return render(request, 'sportsman/sportsman.html', locals()) <QueryDict: {'csrfmiddlewaretoken': ['BzBeiKE82LDcd3tmdzZGSmpOWQatc52SSO7ScEOm7eCVdXsHQWxerSzTZa6KC5xq'], 'first_name': ['test_name'], 'last_name': ['test_name'], '<select name=': ['3']} > -
Adding 'only' before prefetch related slows down query
In pseudocode, I have a db model like this: Model T name tags = models.ManyToManyField(Tag, related_name="Ts") symbol = models.ForeignKey(Symbol) Model Symbol name category = models.ForeignKey(Category) Model Tag name And this is the code I use to export it: query = T.objects.annotate(category=F('symbol__category')).prefetch_related('tags') for t in query: _dict = model_to_dict(t) _dict["category"] = t.category _tags = [] for tag in _dict["tags"] _tags.append(tag.id) _dict["tags"] = _tags In this code, _dict gives me the wanted result. However, T has many other fields I don't need, so I changed query to: T.objects.only("name", "symbol", "tags").annotate(category=F('symbol__category')).prefetch_related('tags') For some reason, this slows down the execution. Original query takes 6 seconds while the last one takes 8 seconds. Why? How can I prefetch everything correctly so that I don't have to loop over tags and append their ids in a dictionary? How can I do this while also using .only()? -
Django rest-auth registration error after creating new user. account_confirm_email not found
I am creating a registration system with Django rest-auth and allauth. Looking at the documentation endpoints, I just used: urls.py app_name = "apis" urlpatterns = [ path('users/', include('users.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/customlogin', CustomLoginView.as_view(), name='rest_login'), path('rest-auth/customlogout', CustomLogoutView.as_view(), name='rest_logout'), path('rest-auth/registration/', include('rest_auth.registration.urls')), ] when I run, a browseable API appears like below: After entering the details and post it, the below error occurs: django.urls.exceptions.NoReverseMatch: Reverse for 'account_confirm_email' not found. 'account_confirm_email' is not a valid view function or pattern name. is there another URL i need to implement (with the name of account_confirm_email) ? I have read the documentations and rest-auth demos on this and it seems I need to include the following urls: url(r'^verify-email/$', VerifyEmailView.as_view(), name='rest_verify_email'), url(r'^account-confirm-email/(?P<key>[-:\w]+)/$', TemplateView.as_view(), name='account_confirm_email'), but this still did not fix the error why is that? -
AttributeError: module 'tagulous' has no attribute 'models' in Django
So I have been building a web app, and for the tags system, I decided to go with django-tagulous. However, when I import it in my models, I am getting this error: AttributeError: module 'tagulous' has no attribute 'models' in Django I have put it in my python INSTALLED_APP list in settings.py, and imported it in models.py, but still get the error. Here is some code. models.py import tagulous class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=75) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to='post_images',blank=True,null=True) published_date = models.DateTimeField(blank=True,null=True,auto_now_add=True) NSFW = models.BooleanField(default=False) spoiler = models.BooleanField(default=False) interests = tagulous.models.TagField() tags = TaggableManager() def __str__(self): return self.title def save(self, *args, **kwargs): super().save(*args, **kwargs) In that Post class, I am using this on the interests one. Here is my forms.py PostForm class PostForm(forms.ModelForm): class Meta(): model = Post fields = ['title','text','image','interests','spoiler','NSFW'] widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'textareaclass editable'}), } def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['image'].required = False So far I have found nothing online about this error. I was expecting it to work, but it didn't Thanks :) -
How to customize the submit and verification method of Django forms?
I've been making my blog project with Django and I was tryting to implement Toast UI Text Editor README, a kind of open source text editor which be be loaded on client web pages. What I'm considering was to locate the text editor inside my form, however, If I do that, I have to remove the CharField named content(which is to be replace with the content of text editor) from forms.py and have to customize sumbit method. But the problem is I don't know how to customize the form submit method or verification method. What I want to do is use the default verification method on client side and if it tells the input is valid, then submit the form data added the content text editor. this is my code. class ArticleCreationForm(forms.Form): do_you_wanna_get_emails = forms.ChoiceField( choices = ( ('option_one', "YES. I wanna get an email once someone reply to you"), ('option_two', "NO. I don't need to get an email.") ), widget = forms.RadioSelect(), initial = 'option_two', ) title = forms.CharField() name = forms.CharField() password = forms.CharField( widget=forms.PasswordInput(), help_text = "Here's more help text" ) email = forms.CharField() ### I removed this field to replace this with the content of Toast … -
DJANGO - upload image stored locally to model ImageField attribute
I have my images downloaded inside the subroot images in my media folder and I'm trying to generate new models which will contain the photo inside the images folder. This is what my model and my view look like: class Post(models.Model): ... image = models.ImageField(upload_to="images", blank=True, null=True) def generate_posts(request): for i in range(20): title_ = f'title{i}' body_ = f'text for post number : {i}' author_ = f'author{i}' network_ = randomize_social() post = Post(title=title_, body=body_, author=author_, social_network=network_) if randomize_picture(): post.image.save("logo.png", File("images/svante.jpg"), save=True) else: post.image = None post.save() areGenerated = True return render(request, "posts/generate_posts.html", {'areGenerated':areGenerated}) The logo.png file is created inside the images folder, but it's blank, 0kb size and when I follow the /generateposts url, I receive this error message: AttributeError at /generateposts 'str' object has no attribute 'read' What can I do to solve this problem? -
how can achieve to Intended query set by this models in django
I have Post model: class Post(models.Model): description = models.CharField( max_length=1500, blank=True, ) school = models.ForeignKey( 'school.School', on_delete=models.CASCADE, null=True ) sibling_uuid = models.CharField(max_length=36, null=True) create_date = models.DateTimeField(default=timezone.now) if Post objects belong to school the sibling_uuid will be random uuid.uuid4 and i will create a post for every class of this school a Post instance with same sibling_uuid . by this way i will know which post should be remove if school's manager removing a school's post.but if i want return a school post to school's manager i need just return one of post per sibling post.(means that from Posts with same sibling_uuid just one of them should be in query set).i'm doing by this way now: school_posts = Post.objects.filter(school__isnull=False).distinct('sibling_uuid') # from every sibling post just on will exist in school_posts classroom_posts = Post.objects.filter(school__isnull=True) all_posts_queryset = sorted(chain(classroom_posts, school_posts), key=attrgetter('create_date'), reverse=True) i want doing above code in a single line to my code be cleaner and i learn ORM better. thank you. -
How to get model from plugin?
My model: class Post(models.Model): title = models.CharField(max_length=100) short_description = models.CharField(max_length=100) image = models.ImageField(upload_to="uploads/images/") content = HTMLField(blank=True) slug = AutoSlugField(always_update=True,populate_from='title', unique=True) date_created = models.DateField(default=datetime.date.today()) CMS Plugin: class PostPlugin(CMSPlugin): post = models.ForeignKey(Post, on_delete=models.CASCADE) Register plugin: @plugin_pool.register_plugin class CMSPostPlugin(CMSPluginBase): model = PostPlugin name = _("Post") render_template = "post/post.html" allow_children = True admin_preview = True module = "subpage" def render(self, context, instance, placeholder): context.update({ 'post':instance.post, 'instance':instance, 'placeholder':placeholder }) return context So, after that, I add this to my table, the intermediate table was created. Here a screenshot. table screenshot So that how I get the plugins: CMSPlugin.objects.filter(plugin_type='CMSPostPlugin', placeholder_id=placehoder.id) after that, I want to get the Post model from this intermediate table, but I don't know how to do that. -
How to return values from database/model after post request in Django Rest framework
I recently started working on django. I am trying to send a location name via post method and then display the list of values from the model on the url or api end point. I am unable to do it. When I send a post request I am not able to view the results on the url/api end point. It displays GET menthod not allowed. This is my views.py class location_details(APIView): def post(self, request, *args, **kwargs): event_id = json.loads(request.body).get('location_name') queryset = customer.objects.filter(eid= event_id) serializer_class = customer_details data = serializers.serialize('json', queryset) return HttpResponse(data, content_type='application/json') How can I display the values based on a post request? I am stuck with this issue for a long time. -
Django admin anotate not work with change list view queryset
I need to create a summary view for a list of records grouped by year, month and category. When I use the model manager and do annotating it works fine, and summary is correctly created. However, if I use the changelist_view request objetcts' queryset it duplicate ungrouped records as well. See the two code listings below. Correct Values: Bill.objects.values_list('category__name', 'year', 'month').annotate(Sum('amount'), due=Sum(F('amount') - F('paid_amount'), output_field=models.FloatField())) <QuerySet [('Insurance', '2019', 'FEB', Decimal('35200.2300000000'), 25200.230000000003), ('Telephone', '2019', 'AUG', Decimal('3353.54000000000'), -23.0), ('Telephone', '2019', 'JUL', Decimal('200'), 200.0)]> Incorrect when used with changelist_view queryset: qs = response.context_data['cl'].queryset extra_context['summary'] = qs.values_list('category__name', 'year', 'month').annotate( Sum('amount'), due=Sum(F('amount') - F('paid_amount'), output_field=models.FloatField())) print(extra_context['summary']) <QuerySet [('Telephone', '2019', 'AUG', Decimal('1677'), -23.0), ('Telephone', '2019', 'JUL', Decimal('500'), 500.0), ('Telephone', '2019', 'AUG', Decimal('1676.54000000000'), 0.0), ('Telephone', '2019', 'JUL', Decimal('-300'), -300.0), ('Insurance', '2019', 'FEB', Decimal('35200.2300000000'), 25200.230000000003)]> Above see that AUG 2019 not grouped correctly. -
What is {% url %} in django?
I have django template: <form id="contactForm" method="get" action="{% url 'contact-form' %}"> ... </form> What is {% url 'contact-form' %} ? -
How to receive a form input in a python script in django?
what i nee is: On a html form when user click the submit button the value of that button to be received as a python variable so that i can use it in my script. My button value is a path to the csv file "CSV/sample_submission.csv" uploaded by user in my app and stored in a folder in my django app. What i want to do is plot some plotly plots by using the file uploaded by the user. I've tried to send the data through the post request and receive it in my view function and render it on html page but what i want is that data to be saved as a global or any type of variable that can be used in any python script in my app. URL.py path("event/",views.event,name="event"), Views.py: def event(request): context={} file= request.POST.get('file',None) context['file']=file return render(request,'main/event.html',context) Following is my code of plot.py from plotly.offline import plot import plotly.graph_objs as go import pandas as pd def get_simple_candlestick(): df = pd.read_csv("FILE PATH RECEIVED FROM FORM") df.head() data = [ go.Bar( x=df['x'], # assign x as the dataframe column 'x' y=df['y'] ) ] layout = go.Layout( title='Plot Title', xaxis=dict( autorange=True ), yaxis=dict( autorange=True ) ) plot_data = … -
The current path, product/, didn't match any of these
I am having trouble with connecting to url code. Everything is showing fine but after I tried to create, this error message pops up. Also, I would like to know if path function works on the django 1.x. '''error message''' Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/product/ Using the URLconf defined in seany.urls, Django tried these URL patterns, in this order: ^admin/ ^$ ^register/$ ^login/$ ^product/create/ The current path, product/, didn't match any of these. '''url.py''' from django.conf.urls import url from django.contrib import admin from seany_user.views import index, registerview, loginview from seany_product.views import productlist, productcreate urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', index), url(r'^register/$', registerview.as_view()), url(r'^login/$', loginview.as_view()), url(r'^product/create/', productcreate.as_view()) ] '''form.py''' from django import forms from seany_product.models import seanyproduct class registerform(forms.Form): name = forms.CharField( error_messages={ 'required': 'enter your goddamn product' }, max_length=64, label='product' ) price = forms.IntegerField( error_messages={ 'required': 'enter your goddamn price' }, label='price' ) description = forms.CharField( error_messages={ 'required': 'enter your goddamn description' }, label='description' ) stock = forms.IntegerField( error_messages={ 'required': 'enter your goddamn stock' }, label='stock' ) def clean(self): cleaned_data = super().clean() name = cleaned_data.get('name') price = cleaned_data.get('price') description = cleaned_data.get('description') stock = cleaned_data.get('stock') if name and price and description and stock: seany_product = product( … -
csrf and cors errors in localhost development of webpacked vuejs/reactjs/angularjs website with django backend
How can I run my vuejs application on localhost and have it send its API calls to my deployed django rest framework backend without getting cors and csrf issues? So far I have these issues: I can't read the cookie from browser because it's domain is not set to localhost. I need that to set the X-CSRFTOKEN header for django. I get CORS errors since localhost is not the same origin as my domain(example.com) I get error that referer does not match. -
How to crop images in django if I already have the cropping data (x,y,etc) coordinates?
I have an app where users would upload images and may crop a part of it so I added cropper.js to capture the coordinates and used a pillow code to crop it , I found it in this blogpost but nothing changes in the images I checked the data type of the coordinates and checked everything and nothing happened. from PIL import Image def crop(corrd, file ,path): image = Image.open(file) cropped_image = image.crop(corrd) resized_image = cropped_image.resize((384, 384), Image.ANTIALIAS) resized_image.save(path) return file if form.is_valid(): image = form.save(commit=False) x = float(request.POST.get('x')) y = float(request.POST.get('y')) w = float(request.POST.get('width')) h = float(request.POST.get('height')) print(x) print(y) print(w) print(h) crop((x,y,w+x,y+h),image.pre_analysed,image.pre_analysed.path) image.patient = patient messages.success(request,"Image added successfully!") image.save() class ImageForm(ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = UploadedImages fields = ('pre_analysed', 'x', 'y', 'width', 'height', ) so what I'm doing wrong here? I tried using opencv but i ran into issues/errors I couldn't fix. -
OSError at /en/ Django Saleor webpack error
I am trying Django Saleor to experience ECommerce framework. But I get this error. And I even tried finding the project root, I couldn't find webapck-bundle.json. This is the error of my django debug page OSError at /en/ Error reading /workspace/saleor/saleor/webpack-bundle.json. Are you sure webpack has generated the file and the path is correct? -
Django ReactJS bundle file not getting building with docker
I am learning docker and dockerizing my Django-react app! It is working now great except an issue and that is the bundle.js file are not getting Django when i run the project through dockcer But bundle.js files are found if run the project without docker! I guess, docker bundle the javascript in a different directory, that is why it is not getting if run with docker! this is my settings.py file STATICFILES_DIRS = [ os.path.join(os.path.join(BASE_DIR, os.pardir), 'dist'), ] and my Dockerfile is given below: FROM node:8 # Name work directory, it can be whatever you want WORKDIR /app COPY . ./ RUN yarn RUN npm run build # Pull base image FROM python:3 # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory, we can name it whatever we want WORKDIR /djangobackend # Install dependencies # Copy requirement file from the docker workdir we defined named djangodocker COPY requirements.txt /djangobackend/ RUN pip install -r requirements.txt # Copy project COPY . /djangobackend/ and this is my dockcer-compose.yml file version: '3.2' services: db: image: postgres:10.1-alpine volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . command: python backend/manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 depends_on: - db volumes: postgres_data: Please know the problem … -
I'd like to know if the ManyToMany Field for each post contains a user ID in django
I'm trying to make a blog web. I want to change the color of the 'like it button' like Instagram depending on whether users like it or not. But I don't know how to build this. views.py def list(self, request, *args, **kwargs): user = request.user if not user.is_authenticated: return redirect('blog:signup') else: response = Blog.objects.filter(owner=user.id) return Response({'posts': response, 'user': user}, template_name='blog/blog_list.html') models.py class Blog(models.Model): title = models.CharField(max_length=255) body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) likes = models.ManyToManyField(User, related_name='likes', blank=True, default='') owner = models.ForeignKey(User, on_delete=models.CASCADE) templates {% for post in posts %} <button type="button" class="like" name="{{ post.pk }}" > {% if post.likes.exist %} <img class="float-left card-icon mx-1 like-img" src="{% static 'blog/like.png' %}" alt=""> {% else %} <img class="float-left card-icon mx-1 like-img" src="{% static 'blog/favorite.png' %}" alt=""> {% endif %} </button> I'm trying to filter in the template. but post.likes.exists is not what I want. This code below is what I exactly want. x = user.likes.through.objects.filter(blog=obj.id, user__id=user.id).exists() Can I implement this code as a template code? Or is there another solution to this? Thank you! -
Django Rest Framework: URL for associated elements
I have the following API endpoints already created and working fine: urls.py: router = DefaultRouter() router.register(r'countries', views.CountriesViewSet, base_name='datapoints') router.register(r'languages', views.LanguageViewSet, base_name='records') Now, I need to create a new endpoint, where I can retrieve the countries associated with one language (let's suppose that one country has just one associated language). For that purpose, I would create a new endpoint with the following URL pattern: /myApp/languages/<language_id>/countries/ How could I express that pattern with the DefaultRouter that I'm already using? -
Implementing PostgreSQL HStore in Django
I found some couple of packages to implement PostgreSQL HStore in Django from djangopackages.org. The most stared and most forked package was last updated in March 2, 2017. I think it is not maintained regularly. But as it at the top of the list I am confused about that should I use it in my project or there is a better option for me. Which is the best and handy way to implement PostgreSQL HStore in Django?