Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Remove packages that are no longer needed from requirements.txt
I just finished my first Django project and wanted to add a requirements.txt. When I type pip freeze I get all the packages in the venv, even the ones I didn't include in my last git commit. How do I get only the packages I used for my last commit? -
How can I unit test Sentry's before_send callback?
I want to write a strip_sensitive_data function and pass it into Sentry's before_send callback, as in the example from their own docs https://docs.sentry.io/error-reporting/configuration/filtering/?platform=python import sentry_sdk def strip_sensitive_data(event, hint): # modify event here return event sentry_sdk.init( before_send=strip_sensitive_data ) I'm working on a Django app and want to find a way to patch or mock this callback using Django TestCase. Is there a simple way to do this? -
How i can get list of data by COLUMN LIKE condition in DRF?
How can I make a request for DRF, as if it would be like a request for SELECT by LIKE condition? Now they are displayed to me like this but I want to output depending on the values in the columns user_id and user_members_id. I have this code models.py from django.contrib.postgres.fields import ArrayField from django.db import models from django.contrib.auth.models import User def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT / user_<id>/<filename> return 'user_{0}/{1}'.format(instance.company.id, filename) # Create your models here. class Company(models.Model): name = models.CharField(max_length=40, blank=True) user_id = models.ForeignKey(User, verbose_name='User', on_delete=models.CASCADE) #models.IntegerField(blank=True) user_members_id = ArrayField(models.IntegerField(), blank=True) date_created= models.DateTimeField(auto_now=True) description = models.TextField(blank=True) # ready = models.CharField(max_length=10, blank=True) STATUSES = ( (1, 'Public'), (2, 'Private'), (3, 'Protected'), ) status = models.IntegerField(verbose_name='Status', choices=STATUSES) THEMES = ( (1, 'Finance'), (2, 'IT'), (3, 'Develop'), (4, 'Building'), ) theme = models.IntegerField(verbose_name='Theme', choices=THEMES) icon = models.ImageField(upload_to = user_directory_path, blank=True) def __str__(self): return self.name serializers.py from rest_framework import serializers from .models import Company class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = '__all__' urls.py from rest_framework import routers from .api import CompanyViewSet router = routers.DefaultRouter() router.register('api/company', CompanyViewSet, 'company') urlpatterns = router.urls views.py from django.shortcuts import render # Create your views here. How get conditinaled result by specify … -
How to remove nbsp and add space in django template
I need to print a contex variable in django template.... my context variable name "content" But this variable containing some html tags and &nbsp... This is my html <div style="max-width:800px;margin:50px auto;padding:0 12px"> <div class="m_-1931231161305542174card" style="background:white;border-radius:0.5rem;padding:2rem;margin-bottom:1rem"> {{ content }} </div> </div> For example my user is entering this Hello, How are you? that context variable containing <p>Hello,</p> <p>&nbsp;</p> <p>How are you??</p> For removing the html tag I have return one funtion I have tried this method def remove_html_tags(text): """Remove html tags from a string""" logger.info(text) clean = re.compile('<.*?>') return re.sub(clean, '', text) def passing_contect(self): ----------------- ---------------------- -------------------) context{'content':remove_html_tags(content)}//passing context without html tags but the o/p is Hello, &nbsp; How are you ???? It still having this &nbsp issue How to handle this -
django send email with celery task
I want to send an email to a user with order.id and "manu_date" of a specific order automatically if the deadline of the order is today. I have already configured celery with rabbitmq and it's working and I'm able to send emails. The problem is I don't know what will go into the tasks and views. So far for the task I have came up with the below task. @shared_task def send_email_task(request): order= Order.objects.all() if order.manu_date > date.today() send_mail('Order Deadline', 'prepare order{{order.id}} before midnight', 'dummyguy1680@gmail.com', ['simarjeetsingh@hotmail.com']) return None class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) address = models.CharField(max_length=100) phone = models.IntegerField(max_length=11) method = (('Pay Upfront', 'Pay Upfront'),('Upon Delivery', 'Upon Delivery'),) shipping_method = models.CharField(max_length = 100, choices = method) language = models.CharField(max_length=30) box = models.CharField(max_length = 30) print_name = models.CharField(max_length=30) Diagnosis_note = models.CharField(max_length=30, blank=True) memo = models.CharField(max_length=100, blank=True) date_created = models.DateTimeField('date_created', default=timezone.now(), blank=False) manu_date = models.DateField('Manufacturing', null=True) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") updated_by = models.ForeignKey(User, null=True, related_name='updated_by_user', on_delete=models.CASCADE) date_updated = models.DateField(max_length=100, null=True) -
Integrate sms API with django prject
i have my django project and i want to integrate it with Etisalat API to be able to send sms to client ,anyone can help me out to integrate SMS API with my project ? -
Download a generated CSV file with Django Rest Framework and ReactJS
I'm trying to download a a simple CSV file to get the email addresses of my users based on when they signed up. I can't seem to get the frontend ReactJS and backend Django to play nice with one another: urls.py ... url(r'^api/email-export/$', app.api_views.EmailExportView.as_view()), ... api_views.py: from rest_framework.views import APIView class EmailExportView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAdminUser] def get(self, request, format=None): user_emails = User.objects.filter(...) response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = "attachment; filename='user_emails.csv'" writer = csv.DictWriter(response, fieldnames=["email"]) writer.writeheader() for email in user_emails: writer.writerow({"email": email}) return response and in my react file import { AdminApiClient } from "./apiClient"; type Props = { apiClient: AdminApiClient; }; export function EmailExportPage({ apiClient }: Props) { const [startDate, setStartDate] = useState(new Date()); const downloadCsv = () => { apiClient.emailExport(startDate) } return ( ... <Form onSubmit={downloadCsv}> <Button type="submit">Download</Button> </Form> ) apiClient.ts is a file with a helper class that performs api calls import axios, { AxiosInstance } from "axios"; export class AdminApiClient { apiToken: string; client: AxiosInstance; async emailExport(query: Date): Promise<any> { const resp = await this.client.get("/api/email-export/", { params: { query }, }); return resp; } } When I hit the download button now, I get a weird error in the terminal: [15/Jul/2020 17:35:16] "GET /api/email-export/?query=2020-07-15T07:34:45.691Z HTTP/1.1" … -
I want to host Django website on Bigrock but there is no "Setup Python App" how do I deploy my Django website?
I am deploying my Django app on bigrock hosting (cpanel) but unable to find "setup python app" now in this case what should I do? I contacted technical support they said "You can't run it as an application on a shared hosting plan" If it can be possible by terminal then let me know the steps or video link so that I can replicate and host my website. No Setup Python App Please suggest the best possible way. -
ValueError: Cannot create form field for 'socket' yet, because its related model 'cpu.socket' has not been loaded yet
So i get the error while i was trying to migrate changes in my models, i thought there's something wrong in the foreign key syntax, but i used this syntax for the accounts login on my other app and it works, so i don't know what's wrong with this one. I've tried to change the order on the models i thought it would solve it but it didn't This is a piece of my models from django.db import models from django.urls import reverse class Cpu(models.Model): name = models.CharField(blank=False, max_length=150) socket = models.CharField(blank=False, max_length=150,default=None) thumb_pic = models.ImageField(upload_to='cpu/',blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("sim:cpu_detail",kwargs={'pk':self.pk}) class Vga(models.Model): name = models.CharField(blank=False, max_length=150) vga_interface = models.CharField(blank=False, max_length=150,default=None) thumb_pic = models.ImageField(upload_to='vga/',blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("sim:vga_detail",kwargs={'pk':self.pk}) class Ram(models.Model): name = models.CharField(blank=False, max_length=150) mem_type = models.CharField(blank=False, max_length=150,default=None) thumb_pic = models.ImageField(upload_to='ram/',blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("sim:ram_detail",kwargs={'pk':self.pk}) class Storage(models.Model): name = models.CharField(blank=False, max_length=150) str_interface = models.CharField(blank=False, max_length=150,default=None) thumb_pic = models.ImageField(upload_to='storage/',blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("sim:storage_detail",kwargs={'pk':self.pk}) class Motherboard(models.Model): name = models.CharField(blank=False, max_length=150) socket = models.ForeignKey("cpu.socket", on_delete=models.CASCADE) mem_type = models.ForeignKey("ram.mem_type", on_delete=models.CASCADE) vga_interface = models.ForeignKey("vga.vga_interface", on_delete=models.CASCADE) thumb_pic = models.ImageField(upload_to='mtb/',blank=True) str_interface = models.ForeignKey("storage.str_interface", on_delete=models.CASCADE) def __str__(self): return (self.name) def get_absolute_url(self): return reverse("sim:mtb_detail",kwargs={'pk':self.pk}) … -
ModuleNotFoundError: No module named 'project.app' while trying to add foreignkey constraint?
models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class CategoryList(models.Model): Category = models.CharField(max_length=200) Cat_Img = models.ImageField(upload_to='cat_media') Active = models.BooleanField(default=True) class ImgDetails(models.Model): Img = models.ImageField(upload_to='media') Category = models.ForeignKey(CategoryList, default=1, on_delete=models.SET_DEFAULT, null=False) keywords = models.CharField(max_length=255) UserDetail = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) Valid = models.BooleanField(default=False) UploadDate = models.DateTimeField(auto_now_add=True) I'm trying to add foreignkey constraint on ImgDetails with CategoryList. It is throwing error from cam_project.cam_app.models import CategoryList ModuleNotFoundError: No module named 'cam_project.cam_app' I tried importing from cam_project.cam_app.models import CategoryList but still no progress. Any suggestions would be appreciated. -
Why do I get "The 'img' attribute has no file associated with it." error in Django?
So I have this simple Django application where users can post diary as well as images. Here, uploading image is optional, so I have left the field as not required. The problem is when I leave the ImageField empty. Saving the post w/o image works fine, but when I try to GET the post, I run into the error. First let me show you the code. models.py class Diary(models.Model): objects = models.Manager() # some other stuff here img = models.ImageField(null=True, blank=True, upload_to="everyday_img") forms.py class DiaryInputForm(forms.ModelForm): # some other stuff here. img = forms.ImageField(required=False) views.py def InputDiary(request): form = DiaryInputForm(initial={'authuser':request.user}) if request.method == 'POST': form = DiaryInputForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.authuser = request.user # some other stuff here user_img = request.FILES.get('img', None) instance.save() return redirect('/diary/diarymain') return render(request,'diary/diaryinput.html', {'form':form}) def ViewDiary(request, authuser_id, slug): today = Diary.objects.get(slug=slug) return render(request, 'diary/diaryview.html', {'today' : today}) diaryview.html ... <div class="row justify-content-center"> <div class="col col-12"> <div class="detail-contents"> <img src="{{today.img.url}}" class="user-img"><br> {{today.what|safe}} </div> </div> </div> ... So when diaryview.html is loaded, the error occurs. I know it's obviously because the img column has no data, but I have no idea on how I should deal with it. Thank you very much in advance. :) -
How to search product in Django?
I am trying to create a search functionality in Django, I have some data store in my Django table and i am searching product name, but I am getting blank output, Please check my code and let me know where I am Mistaking. Here is my urls.py file... from .views import SearchResultsView urlpatterns = [ path('search', SearchResultsView.as_view(), name='search_results'), ] here are my views.py file from django.views.generic import ListView from django.db.models import Q class SearchResultsView(ListView): model = Product template_name = 'mainpage/search-product.html' #prod=Product.objects.all() def get_queryset(self): query = self.request.GET.get('search') products=Product.objects.filter(Q(name__icontains=query)) return products here are my base.html file... <form action="/search" method="get"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" name="search" id="search exampleInputPassword1" placeholder="Search a Product"> </div> <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i></button> </form> -
How can I directly put a model data into another form's input in Django?
I made a register page and a checkout page(named thankyou in my code) and then i integrated a payment gateway API with my checkout page's form. The problem I'm getting is, I want to choose the amount of payment from another model's attribute, which I created for the registration page. To be clear, I want to use 'Membership' model's data which the user just entered in Registration page(forms.html) and put it in the amount variable of Thankyou function. Here's the model.py from django.db import models # Create your models here class MyUser(models.Model): image = models.ImageField(upload_to='profile_pics',blank=True) Full_name = models.CharField(max_length=256) GENDER = (('M','Male'),('F','Female'),('O','Other')) gender = models.CharField(max_length=1, choices=GENDER, null=True) Phone_Number = models.CharField(max_length=12,unique=True) Email = models.EmailField(max_length=264,unique=True) Country = models.CharField(max_length=264) State = models.CharField(max_length=264) City = models.CharField(max_length=264) Address = models.CharField(max_length=2048) MEMBERS = [ ('2100','2100 Rs Lifetime Membership'), ('21000','21000 Rs Lifetime Patron Membership'), ('100000','1Lakh Rs S.A.F Trustee'), ('1100000','11Lakh Rs S.A.F Patron Trustee'), ('5100000','51Lakh Rs S.A.F Board of Trustee'), ] Membership = models.CharField(max_length=6,choices=MEMBERS, null=True) CAREERS = [ ('BI','Business & Industry'), ('JL','Judicial & Legal Services'), ('BP','Bureaucrats & Public Servant'), ('DP','Defence, Police & Paramilitary Forces'), ('NC','NCC Cadets'), ('VJ','VIPR Jan(Pujari/Brahmins)'), ('PR','Public Representatives'), ('NF','Nandanaar Families'), ('SO','Social Organisations'), ('DO','Doctors'), ('YO','Youths'), ('OT','Others'), ] Career = models.CharField(max_length=264,choices=CAREERS,null=True) def __str__(self): return str(self.Full_name) Here's the views.py from … -
Django, prefetch related raises key error
I have a query which executes a reverse prefetch related. But raises the following error: KeyError at /api/group/ (1,) which is rather ambiguous. My models: class Farm(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) """ Farm Data """ name = models.CharField(max_length=255, unique=True, ) farm_id = models.CharField(max_length=255, help_text=FarmHelpTexts.FARM_ID, primary_key=True) lose_certificate_on = models.DateField(blank=False) time_zone = models.CharField(max_length=255, help_text="The Time Zone of the farm.") # Some more field Herd Model: class Herd(models.Model): farm = models.ForeignKey(to=Farm, on_delete=models.CASCADE, null=False, related_name='herds') name = models.CharField(max_length=255) def __str__(self): return self.name my view: class GroupView(ModelViewSet): filter_backends = GROUP_FILTERS def get_queryset(self): # TODO: # When the auth schema is chosen is set up it's gonna be .filter(user = self.request.user) query_set = Farm.objects.filter(pk=1).prefetch_related('herds') return query_set serializer_class = FarmSerializer Now, I don't if it's relevant but the Herd model is a related object as well (group) which in turn as another related object (cow). the Group model also has a foreign key to itself. all the models have a foreign key and all of them have related names. -
Django Image File handling
Suppose I have a model Person, something like that: class Person(models.Model): first_name = Models.CharField(....) last_name = Models.CharField(....) Now, I want to add a user profile image. I have thought about adding the ImageField directly or 'wrapping' it in my own custom model and adding a FK to the Person model, with the wrapper looking like that: class MyImageField(models.Model): image = models.ImageField() uploaded_at = models.DateTimeField(...) description = models.CharText(...) owner = models.ForeignKey(Person) #... other fields for meta data as needed class Person(models.Model): ... profile_picture = models.ForeignKey(MyImageField) Would this approach be beneficial? I think, using a custom model has a few benefits: More flexibility in terms of storing associated meta data Expandable Could be kept generic for all usecases where images are needed (User profile, gallery, etc.) Single point for encoding filenames, as creating a hash as filename seems better than storing the file under the original name for avoiding duplicate names (as django normally does, as I understand it) Possibility of adding an owner property, to allow for easier access control (Check if accessing user is owner, or in the same group or whatever) Regarding the last part, since images (and files) are stored on the servers file system and not in … -
Bootstrap selectors not making much sense
I'm brand new to using Bootstrap and I'm having a tough time understanding the basic logic of it. I understand the idea behind some of it, but other things completely perplex me and I can't find too many resources that explain it without referring to other concepts I'm totally unaware of. I'm wondering if someone can give me a hand with working through what different selectors are for. Here's some example code copied straight from Python Crash Course (from a project where Django is used to build a web app and Bootstrap 4 is used to style it): <body> <nav class="navbar navbar-expand-md navbar-light bg-light mb-4 border"> <a class="navbar-brand" href="{% url 'learning_logs:index' %}"> Learning Log</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span></button> <div class ="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'learning_logs:topics' %}"> Topics</a></li> </ul> What I (think) I know: From what I've been able to understand from the documentation & experimenting, assigning a class to an HTML element pulls premade style rules from somewhere in the background and applies them to my project, so <nav class="navbar navbar-expand-md navbar-light bg-light mb-4 border"> would tell Bootstrap that this is a navbar (from navbar), … -
Django-ldap authentication issue: user DN/password was rejected by ldap server
I am receiving the below (on django console) although i am entering the right password. I am guessing it's an issue with DN. However, couldn't understand what is wrong as i am searching for user with uid at dc level, with all the sub-trees in scope (2), that returns an object. search_s('dc=zl,dc=local', 2, 'uid=%(user)s') returned 1 objects: cn=abler bill,ou=credit,ou=zltest,dc=zl,dc=local Authentication failed for abill: user DN/password rejected by LDAP server. Please suggest. -
Creating student accounts using django admin and using them for login
Hi I wanted to create user accounts from django admin pannel and then use the email and passsword stored in the model to login? def login_view(request): context = {} user = request.user if user.is_authenticated: return redirect("home") if request.POST: form = AccountAuthenticationForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) return redirect("home") else: form = AccountAuthenticationForm() context['login_form'] = form return render(request, 'login.html', context) forms.py class AccountAuthenticationForm(forms.ModelForm):' password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model=Account fields = ('email', 'password') def clean(self): if self.is_valid(): email = self.cleaned_data['email'] password = self.cleaned_data['password'] if not authenticate(email=email, password=password): raise forms.ValidationError("Invalid login") models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") user = self.model( email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined=models.DateTimeField(verbose_name='datejoined',auto_now_add=True) last_login= models.DateTimeField(verbose_name='last login', auto_now=True) is_admin= models.BooleanField(default=False) is_active= models.BooleanField(default=True) is_staff= models.BooleanField(default=False) is_superuser= models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, … -
I'm trying to work with Django and have been trying to design an Encyclopedia. Not been able to proceed
I have been trying to work with Django to make an encyclopedia. I have automated almost everything but there are a few things I havent been able to do. When i set debug mode to false, i cannot access the static files. When I set it to true, I cannot change the error page. What do I do? I want to have a link on every entry page that changes the text area so that it can be edited. I havent been able to do this. Attaching views.py and url.py views.py import markdown2 from . import util from django import forms from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse import random class NewForm(forms.Form): Title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), label="Title") Content = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'}), label="Content") def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries(), }) def getpage(request, pagename): text = util.get_entry(pagename) return render(request, "encyclopedia/content.html", { "pagename": pagename.upper(), "editpage": pagename+".edit", "content": markdown2.markdown(text), "getpage": True }) # def err404(request,exception): # return render(request, "encyclopedia/content.html", { # "pagename": "Page Not Found : Error 404", # "content": "Oops... Error 404 : Page Not Found!" # }) def editpage(request,pagename2): Pagename=pagename2.upper() text = util.get_entry(pagename2) form = NewForm(initial={'Title' : Pagename, 'Content' : markdown2.markdown(text)}) types = "warning" errmsg = "Please Check … -
Error Installing django-misaka, Windows 7 Python 3.7.7 32 BIT
Recently I Tried To Install pip install django-misaka While I Was Installing This I Got Two Errors- 1.error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://visualstudio.com/visual-cpp-build-tools I Solved This Error On My Own By Going To The Helper Link and downloaded the so called "Visual C++ 14.00" That costed my around 4.6 GB! (Also Rebooted My Computer) error: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe' failed with exit status 2 I Also Refereed Many Forums And Posts On Stackoverflow and Github Issues But Didn't Find Any Related or problem solving answers! I Tried To Solve This Many-Many Times But Could Not Get Over This Error!, I Dont What Is Happening Over PLEASE HELP ME! -
Django Rest Framework: Accessing validated_data outside of def create() method
so I know my question is horribly written but I'm not sure the best way to phrase this. Let me explain. I'm trying to get my serializer class to process multiple value types for a specific field. For example, I need to Post the JSON values of items called "Temp (C)", "Humidity(%)", etc all under a specific field called "value" in my serializer class. I also of course have a model in models.py called "value". This is what I have so far: models.py class DataValueTable(models.Model): timestamp = models.FloatField() sensorName = models.TextField(null=True) value = models.FloatField() views.py class DataValueTableList(APIView): parser_classes = [JSONParser] authentication_classes = [] permission_classes = [] def post(self, request, format=None): serializer = DataValueTableSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py class DataValueTableSerializer(serializers.ModelSerializer): class Meta: model = DataValueTable fields = ['id', 'System Time', 'Node ID', 'Temp (C)', 'Humidity(%)', 'Pyra (WPM)',] extra_kwargs = { "Node ID": {"source": "sensorName"}, "System Time": {"source": "timestamp"}, "Temp (C)": {"source": "value"}, "Humidity(%)": {"source": "value"}, "Pyra (WPM)": {"source": "value"}, } def create(self, validated_data): return DataValueTable.objects.create(**validated_data) For the serializer.py: The values im posting as JSON are different than the model names in models.py so I'm using "extra_kwargs" to map the JSON names to the models. Here's … -
Unable to import django.contrib
I have just started to Django and downloaded a project from the internet specifically cs50 web programming HARVARD. I had just downloaded ... and I see some import errors please help me out here ..really stuck over here! also, my default system is running on python 2.7 and for django I use python3 and in vs code 3.7. enter image description here -
Django-guardian get all obects user can view including anonymousUser?
I'm starting to play around with django guardian and I'm trying to understand how folks use this to display both restricted and unrestricted objects to a user. Based on my understanding of the docs, anything that should be "world viewable" should have the view_model attribute assigned to the AnonymousUser account for each object. This makes sense, but I am curious how to efficiently display objects to an authenticated user where the user has view permissions and AnonymousUser has view permission. If there is no user currently authenticated the objects assigned to AnonymousUser are all displayed, but what is the best way to display all objects to an authenticated user, which include objects only that user can view and anything assigned to the AnonymousUser? Right now this is my solution: def myView(request, template_name = "app/template.html"): MyStuff = get_objects_for_user(request.user, 'app.view_mymodel') AnonymousUser = User.objects.get(username='AnonymousUser') AnonStuff = get_objects_for_user(AnonymousUser, 'app.view_mymodel') MyStuff = MyStuff.union(AnonStuff) return render(request, template_name, {'MyStuff': MyStuff}) Is there a more straight forward way to return all objects a user can view and the anonymous user can view? Or is there a different way to make an object viewable by everyone that doesn't involve the anonymousUser account when using guardian so that it is … -
How to add dynamic meta tags to react app based on Django API
I have a React front-end and a Django (DRF) API. The React front-end has a route like /content/:id where a different page with a different image is rendered depending on the :id. I'd like to change the index.html meta tags based off the content from that request which comes from Django. There are many tutorials on how to do this with express and React: http://www.kapwing.com/blog/how-to-add-dynamic-meta-tags-server-side-with-create-react-app/ but how can I do it with a Django back-end? The files are also stored on AWS S3. -
Update related model field through a view (Django REST)
class Question(models.Model): ... posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # following fields are for sorting by popularity popular_param = models.BigIntegerField(default=0) class Answer(models.Model): question = models.ForeignKey(Question, related_name='answers', on_delete=models.CASCADE) ... posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) What I want to achieve: Whenever an Answer is created, popular_param of the Question model should be incremented by 10. I have tried the following, by overriding perform_create in the viewset. class PostAnswerViewSet(viewsets.ModelViewSet): """ this is where you post answers """ queryset = Answer.objects.all() serializer_class = PostAnswerSerializer def perform_create(self, serializer): answer = self.get_object() answer.question.popular_param = F('popular_param') + 10 answer.question.save() serializer.save() OR def perform_create(self, serializer): Answer.question.popular_param = F('popular_param') + 10 Answer.question.save() serializer.save() I seem to be missing some syntax but can't figure out what. None of the other questions on SO have helped so far.