Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Plesk passenger django watch manage.py logs
I am using django over Plesk. For this, it is necessary to install passengers in plesk. https://support.plesk.com/hc/en-us/articles/115002701209-How-to-allow-installing-and-install-Django-applications- When I write python manage.py runserver while working on localhost, I can watch all manage.py logs instantly. But since I am not running this command while working on this plesk passenger, I cannot see any log record. How can I watch manage.py log records instantly? -
Serializers reverse update DRF
Question is .. How can I update Course by ID in a same time if need to update also Status fields for this course? such as name, date. Status is unique per course&users. My view: class CourseEditView(ModelViewSet): serializer_class = CourseSerializer queryset = Course.objects.all() http_method_names = ['patch'] My wrong serializer: class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course My models: class Status(models.Model): name = models.CharField(max_length=256, blank=True) date = models.DateField(blank=True, null=True) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="courses") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADErelated_name="students") class Meta: verbose_name_plural = 'Statuses' verbose_name = 'Status' unique_together = ('user', 'course') class TrainingCourse(models.Model): name = models.CharField(max_length=255) -
How to set default celery queue?
My celery settings in django: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_QUEUES = ( Queue('high', routing_key='high'), Queue('normal', routing_key='normal'), ) CELERY_DEFAULT_QUEUE = 'normal' If I set queue name in my task, it's works. But if I don't, default queue settings doesn't work. # It's ok @periodic_task(run_every=timedelta(minutes=10), name='Delete props', queue='normal') def delete_props(): delete_props() # It doesn't work @periodic_task(run_every=timedelta(minutes=10), name='Delete props') def delete_props(): delete_props() How to set default queue and don't set in in task parameters? -
Is there a way to accelerate Celery Beat with multiple servers?
I have set up my Celery Beat successfully and it executes my tasks exactly like I expect it to. The problem I am facing is that my task is very long. To give you a little more context I am calling an API function every 30 minutes that query some thousands stocks from the stock market and then proceeds to slightly modify and adapt the newly acquired data. Those manipulation are unfortunately essential but are very power hungry. This tasks takes me around 30-35 minutes to complete, which means sometimes my function is not done before the other function is triggered by Celery Beat. This causes my database to store the data in a imperfect chronological order. I planned to query this data every 20 minutes but the delay is forcing me to reconsider. Now even 30 minutes is not enough and I plan to add many other quirks to my function, potentially delaying this query even more. Is there a way for me to split the workload of my function across multiple celery beat servers? I could easily separate my complete stock list in multiple smaller lists that could then be dispatched to different Celery Beat servers so they … -
Why i cannot use gmail smtp in django?
This is my setting: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'prahbari82@gmail.com' EMAIL_HOST_PASSWORD = 'My gmail password' EMAIL_PORT = 587 EMAIL_USE_TLS = True and i use CBV's: from django.contrib.auth import views as auth_views from django.urls import reverse_lazy class UserLogin(auth_views.LoginView): template_name = 'accounts/login.html' class UserPassReset(auth_views.PasswordResetView): template_name = 'accounts/password_reset_form.html' success_url = reverse_lazy('accounts:password_reset_done') email_template_name = 'accounts/password_reset_email.html' class PasswordResetDone(auth_views.PasswordResetDoneView): template_name = 'accounts/reset_done.html' class PasswordResetConfirm(auth_views.PasswordResetConfirmView): template_name = 'accounts/password_reset_confirm.html' success_url = reverse_lazy('accounts:password_reset_complete') class PasswordResetComplete(auth_views.PasswordResetCompleteView): template_name = 'accounts/password_reset_complete.html' But I don't get any errors I also turned on the less secure app! I also use 2 verification but it does not work! -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.UserModel' that has not been installed
I am trying to add an uuid field to the AbstractUser model. When running makemigrations it throws the following error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.UserModel' that has not been installed accounts/models.py import uuid from django.db import models from django.contrib.auth.models import AbstractUser class UserModel(AbstractUser): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Meta: app_label = 'app_auth' db_table = 'user_accounts' def __str__(self): return self.username settings.py INSTALLED_APPS = [ # Django 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # My Apps 'accounts', ] AUTH_USER_MODEL = 'accounts.UserModel' The solutions suggested here didn't help. -
How to use a placeholder inside Django CMS Plugin?
cms_plugin.py @plugin_pool.register_plugin class CarouselPlugin(CMSPluginBase): name = _("Carousel") model = CarouselPluginModel exclude = ['slides'] inlines = [CarouselSlideInline] render_template = "plugins/touts/carousel.html" def render(self, context, instance, placeholder): context['instance'] = instance return context models.py class CarouselPluginModel(CMSPlugin): slides = models.ManyToManyField('CarouselSlide', blank=True, related_name='slider_images') content = PlaceholderField('content') def slide_list(self): return CarouselSlide.objects.filter(carousel=self).order_by('order') def copy_relations(self, oldinstance): self.slides = oldinstance.slides.all() plugins/touts/carousel.html {% load i18n staticfiles cms_tags menu_tags sekizai_tags %} <div class="carousel"> {% render_placeholder instance.content %} <div class="carousel__slider"> {% for slide in instance.slide_list %} <div class="carousel__slider__slide" style="background-image: url('{{slide.image.url}}')"> <div class="carousel__heading"><h1>{{slide.title}}</h1></div> <div class="carousel__sub-heading"> <p>{{slide.sub_title}}</p> </div> {% if slide.button_link %} <a href="{{slide.button_link}}" class="carousel__button button-1">Learn More</a> {% endif %} </div> {% endfor %} </div> </div> I am planning to have two different CMS plugin named as 'Carousel' and 'Carousel Slide'. And as you can guess from their name, I'm trying to put placeholder inside of Carousel plugin so I can put Carousel Slides inside. It looks like CMS Plugin inside CMS Plugin. How can I achieve that kind of structure? -
Iterating Over Static CSS File Names Are Not Displaying The Styles
I have been trying to load static CSS files using an array containing CSS file names. For some reason, even though the file path is correct, the stylesheets don't load. It only occurs while they are being loaded in a for loop and not if they are hard coded 1 by 1. For example, here is what I am trying to render in my views file: def about(request): context = { 'headerCSS': [ 'mysite/css/about.css' ] } return render(request, 'mysite/about.html', context) I then try to load it like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> {% if headerCSS %} {% for iter in headerCSS %} {% with iter as css %} <link rel='stlyesheet' href="{% static css %}"/> {% endwith %} {% endfor %} {% endif %} </head> This is the link that gets created but doesn't work: <link rel='stylesheet' href='/static/mysite/css/about.css'/> However, if I add it without the for loop like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="{% static 'mysite/css/about.css' %}"> </head> It produces the same link: <link rel='stylesheet' href='/static/mysite/css/about.css'/> Everything works fine even when I just assign the … -
How to replace element on a model data base on django
the question is simple, I want to replace the "content" text data in the database. But I dont know how, I am kinda new to django! thank you for now, it add a new item on my database, But i just want to modify an item that is already on my database. Thanks for the help models.py class number(models.Model): item = models.CharField(max_length=100) content = models.TextField() def __str__(self): return self.item views.py def promo(request): form = numberform() if request.method == "POST": form = numberform(request.POST) if form.is_valid(): numberclean = form.cleaned_data["num"] print(numberclean) test = number(item="numberall", content=numberclean) test.save() else: form = numberform() return render(request, "promo/home.html", {"form": form}) return render(request, "promo/home.html", {"form": form}) forms.py class numberform(ModelForm): class Meta: model = number fields = ["num"] -
UWSGI Multi-site performance decrease after some days active
I have a multi-site server with Nginx and uwsgi running Django instances, and I had noticed that the performance decrease after some days running. I have 8 sites with not more than 100 visits per day in total. If I run Google insights I have 95/100 points in mobile, but after some days I get 80/100 (same page). When I restart uwsgi I get 95 again, the difference could not be very noticeable but google kick my sites from first page results. I think the problem could be in the uwsgi configuration. The server is t2.micro aws instance, 1 cpu 1gb ram. My /etc/systemd/system/uwsgi.service file is: [Unit] Description=uWSGI Emperor service After=syslog.target [Service] ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target And all ini files in /etc/uwsgi/sites have this configuration: [uwsgi] project = kioner uid = ubuntu base = /home/%(uid) chdir = %(base)/%(project) module = %(project).wsgi:application env=DJANGO_SETTINGS_MODULE=%(project).settings_pro socket=/home/ubuntu/server-config/%(project).sock chmod-socket=666 vacuum=true master = true processes = 1 logto = /var/log/uwsgi/%n.log The system information at this moment is: System load: 0.0 Usage of /: 64.2% of 7.69GB Memory usage: 78% Swap usage: 0% Processes: 114 Is the configuration good for multi-sites? What can I do to know what is causing that? … -
How to update variable in d3 chart using ajax in django
I will update data variable in d3 chart scripts without refreshing the screen using ajax which the variable sent from view.py. How to update it, the variable in d3 chart is {{totalSalesGraph|safe}} htmlFile.html <html> <div class="graphTotalSale"> <div id="graphSale"></div> </div> <script> setInterval(function() { $.ajax({ type: "GET", url: "{% url 'updateData' %}" }) .done(function(response) { // how to update {{totalSalesGraph}} variable in d3 chart. (new value is response.totalSalesGraph) }); }, 5000) </script> <script> var margin = {top: 10, right: 30, bottom: 30, left: 60}, width = 550 height = 120 var svg = d3.select("#graphSale") ... //Read the data var data = {{totalSalesGraph|safe}} ... </script> <html> -
How to get list POST request in django
get post in webservice but dont get list label = request.POST.getlist('label') but label is string value: "label": "['s, l']" this value not list how to get list in django? I uses postman. -
How to store data from html form to postgres database?
I have an HTML form from which data needs to be stored in the Database. My project structure is as: Form - _init_.py - settings.py - urls.py - wsgi.py - manage.py Please list the process for this. I am confused whether there is a need to create a new app(using - manage.py startapp app_name) to display the form or it can be done without a new app. -
How do I enable caching on a django development server?
I am running a development server for Django. I understand the default behaviour is to set Cache-Control: no-cache and Pragma:no-cache in the request headers, however I would like to allow file caching so I can get a better appreciation of page speed. How do I enable caching on a django development server? Per the docs, I have set up a DummyCache and associated middleware but this does not appear to solve the problem. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_KEY_PREFIX = '' CACHE_MIDDLEWARE_SECONDS = 600 I've also been sure to update the middleware with the additional modules (abbreviated for clarity below): MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] -
How do I create a PDF constancy in Reportlab using Django 2 and Python 3?
# PDF Certificates in Reportlab I've been trying to make a certificate but I couldn't class NumberedCanvas(canvas.Canvas): def __init__(self, *args, **kwargs): canvas.Canvas.__init__(self, *args, **kwargs) self._saved_page_states = [] def showPage(self): self._saved_page_states.append(dict(self.__dict__)) self._startPage() def save(self): """add page info to each page (page x of y)""" num_pages = len(self._saved_page_states) for state in self._saved_page_states: self.__dict__.update(state) self.draw_page_number(num_pages) canvas.Canvas.showPage(self) canvas.Canvas.save(self) def draw_page_number(self, page_count): # Change the position of this to wherever you want the page number to be self.setFont('Helvetica', 8) self.drawRightString(211 * mm, 15 * mm + (0.2 * inch), "Page %d of %d" % (self._pageNumber, page_count)) # Part I is a class that contains the model data ACCOUNT PDF CLASS # --------------------------------------_------------------------------------ PART 1 class ExportPDFAccount: def __init__(self, query): self.buffer = BytesIO() self.pagesize = letter self.query = query self.width, self.height = self.pagesize @staticmethod def _header_footer(canvas, doc): canvas.saveState() title = "Estado de cuentas" canvas.setTitle(title) styles = getSampleStyleSheet() # custom styles styles.add(ParagraphStyle('set_title', alignment=TA_LEFT, fontSize=14, fontName="Helvetica-Bold", )) PART 2 # PARTE 2 url = "https://static.coinbtr.com/static/img/coinbtr_logo.png" r = requests.get(url) image = ImageReader(Image.open(BytesIO(r.content))) canvas.drawImage(image, 35, 600, width=8*cm, height=8*cm, preserveAspectRatio=True) set_title = Paragraph(title.upper(), styles['set_title']) set_title.wrap(doc.width + 250, doc.topMargin) set_title.drawOn(canvas, 215, doc.height + doc.topMargin - 40) PART 3 data = [('#', 'Fecha', 'Método', 'Estatus', 'Sub-total', 'Comisión')] set_table = Table(data, colWidths=[35, 100, 100, … -
Does Cookie expiration differs in chrome and firefox?
I have been working with cookies. so watched the docs and some blogs and code the cookies just like below--> def ProouctDetailView(request, slug): item = Item.objects.get(slug=slug) response = render(request, 'product.html', {'item' : item } ) temp = request.COOKIES.get('pro', None) response.set_cookie('pro','{0} {1}'.format(temp, slug)) return response Here I am getting the cookies. As django doesn't provide setting multipe values in a single cookie, I am getting all values together as a string(seperated by a space) and spliting them using split() method. Then I filter to generate the queryset for recently viewed section def HomeListView(request): items = Item.objects.all() recent = None try: slug = request.COOKIES.get('pro').split(" ") recent = Item.objects.filter(slug__in= slug) except: pass return render(request, 'home.html', {'items': items, 'recent':recent}) From cookies,What I am getting are slugs of the items object so that later I can show them in recently viewed section as i didn't provide any max_age field in my set_cookie() method it will set as none which means this cookie will auto expire when user closes the browser session, means shuts down the browser,Right? But the recently viewed section doesn't expires even if I shut down the chrome and restart the chrome. It still there. so the cookie didn't expired in chrome . … -
How to serve dist folder of Vue together with Django using nginx?
I have developed a restful api using Django and I have developed an admin panel using Vue and I have a dist folder. I have bought one VPS (Virtual Private Server). I want to deploy both of them in one server and use Vue developed admin panel instead of default one. I have tried to serve it through django templates and eventually it did not work. I have converted all static url accesses to django like static access urls but it could not find sources which .js files access by loading other sources. How can I handle it using nginx? -
How to get data from form html and formatting to link
I already make website with some form input in html, i need to get my input data, and make it whatsapp link for example, this it my input data and this is my code from input html <section id="contact"> <div class="container"> <h1>Contact Us</h1> <div class=row> <div class="col-md-12"> <form class="contact-form"> <div class="form-group"> <input type="text" class="form-control" placeholder="Your Name" name="nama"> </div> <div class="form-group"> <input type="number" class="form-control" placeholder="Phone Number"> </div> <div class="form-group"> <label for="exampleFormControlSelect2">Pilih Jenis Paket</label> <select multiple class="form-control" id="exampleFormControlSelect2" name="paket"> {% for packet in products %} <option > {{ packet.name }} | Rp {{packet.price}}</option> {% endfor %} </select> </div> <div class="form-group"> <textarea class="form-control" rows="4" placeholder="Your Message"></textarea> </div> <button type="submit" class="btn btn-primary" >Send Message</button> </form> </div> </div> </div> </section> for example the link should be likethis https://api.whatsapp.com/send?phone=628981234567&text=PAKET%205%20HARI%204%20MALAM|Rp%202500000 how can I make this link with just click on Send Message button? -
Filtering querysets in Django Rest Framework
Today i have a really strange behoviour. I have added a custom mixin to my User Viewset to filter the users by username and password and other fields. the code look like the following: class MultipleFieldLookupMixin(object): """ Apply this mixin to any view or viewset to get multiple field filtering based on a `lookup_fields` attribute, instead of the default single field filtering. """ def get_object(self): queryset = self.get_queryset() # Get the base queryset queryset = self.filter_queryset(queryset) # Apply any filter backends filter = {} for field in self.lookup_fields: if self.kwargs[field] is not None: # Ignore empty fields. filter[field] = self.kwargs[field] obj = get_object_or_404(queryset, **filter) # Lookup the object return obj class UserView(MultipleFieldLookupMixin, viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_fields = ['username', 'pwd', 'token_confirm', 'email', 'token_cng_pwd'] i would like the list operation to filter the queryset in every given parameter (so None if none is avalable and all if all are available). But the list endpoint continues to show every user to me, without filtering them. Where am i wrong? Do i have to manually set a filterbackend? am I doing some stupid mistake? Thanks a lot -
Django Like button working for all posts, but not showing with the change of button in Homepage
I have this like button, it works fine for the first post, but for all the other posts below it, it doesn't show any change of button instead the button changes in the first post, but the like gets registered for those specific posts without changing the like for first post. Its quite a weird situation to explain as I am not much familiar with js. view def like_post(request, slug): user = request.user post = get_object_or_404(Post, slug=slug) is_liked = False if user in post.likes.all(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True # return redirect('posts:myhome') context = { 'post':post, 'is_liked':is_liked, 'total_likes':post.total_likes() } if request.is_ajax(): html = render_to_string('posts/like_snippet.html', context, request=request) return JsonResponse({'form': html}) like snippet.html <form action="{% url 'posts:like_post' post.slug %}" method="post">{% csrf_token %} {% if user in post.likes.all %} <a id="like" name="post_id" value="{% url 'posts:like_post' post.slug %}" class="like-btn">{{ post.likes.count}} <i class="fas fa-heart fa-lg" style="color: red;"></i></a> {% else %} <a id="like" name="post_id" value="{% url 'posts:like_post' post.slug %}" class="like-btn">{{ post.likes.count}} <i class="far fa-heart fa-lg" style="color: red;"></i></a> {% endif %} </form> html div function in homepage <div id="like-snip" class="like_snippet mt-1"> {% include 'posts/like_snippet.html' %} <div> js $(document).ready(function(event){ $(document).on('click', '.like-btn', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: pk, data: {'csrfmiddlewaretoken': … -
How can i use annotate in the ModelSerializer
I have a FooModelSerializer. I want to show count of some field which is can show with Model.objects.annotate(c=Count(some_field)). So if i write queryset as above as in the ModelViewSet, works correctly but another BarModelSerializer include this FooModelSerializer. As i dont write queryset in BarModelSerializer, FooModelSerializer won't show count of some field. Now that i want to show count of some field when FooModelSerializer calls. So how can i override queryset in ModelSerializer. I've tried override to to_representation(instance) function but instance parameter is not query so i cant add annotate. FooModelSerializer(serializers.ModelSerializer): c = serializers.IntegerField() class Meta: model = Foo fields = ('some_field', 'annotate_field', 'c') BarModelSerializer(serializers.ModelSerializer): foo = FooModelSerializer() class Meta: model = Bar fields = ('foo',) -
How to filter Django Form dropdown for currently logged-in user (Class Based Views)
I have the two models, Fillup and Car, and the Fillup model has a Foreign key (for recording times you fill up your car with gas, for example), and in the form to create a new Fillup, I want to limit the dropdown for the Car field to only Cars associated with the current user, but right now it's showing all users cars. I've seen a couple solutions that involve passing the request into the form from the view but I can't figure out how to do it using the Class Based Views I currently have set up. Here's my code: models.py class Fillup(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) date = models.DateField(default=date.today) price_per_gallon = models.FloatField() trip_distance = models.FloatField() gallons = models.FloatField() car = models.ForeignKey('Car',on_delete=models.CASCADE) @property def total_sale(self): return round(self.price_per_gallon*self.gallons, 2) @property def mpg(self): return round(self.trip_distance/self.gallons, 4) class Car(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=25) make = models.CharField(max_length=25) model = models.CharField(max_length=25) model_year = models.IntegerField(choices=MODEL_YEARS) status = models.BooleanField(choices=STATUS) def __str__(self): return self.name views.py class FillupListView(ListView): model = Fillup context_object_name = 'fillup_list' ordering = ['-date'] # NOT USING THIS YET # def get_queryset(self): # return Fillup.objects.filter(user=self.request.user) class CarListView(ListView): model = Car ordering = ['name'] class NewFillup(LoginRequiredMixin,CreateView): model = Fillup fields = ('date', 'price_per_gallon', 'trip_distance', 'gallons', … -
invalid dsn: invalid connection option "postgis_extension"
On localhost everything is working fine. But I am having problems with https://rossdjangoapp.herokuapp.com/. I tried to follow this tutorial https://medium.com/the-geospatials/deploy-geodjango-application-to-heroku-in-2019-part-3-41ca4535f377. I got the below error messages. remote: -----> App not compatible with buildpack: https://github.com/peterkeen/heroku-buildpack- remote: ! The GDAL, GEOS and PROJ binaries and BUILD_WITH_GEO_LIBRARIES functonality are now deprecated. remote: ! An alternative buildpack to enable GDAL, GEOS and PROJ use is available here - https://github.com/heroku/heroku-geo-buildpack remote: ### WARNING: THIS BUILDPACK HAS BEEN DEPRECATED remote: Please check https://git.io/fj5QW These are the build packs I now have. I want to add map functionality to my site. settings.py import os if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] GDAL_LIBRARY_PATH = r'C:\OSGeo4W64\bin\gdal300.dll' import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = True ALLOWED_HOSTS = ['rossdjangoawesomeapp.herokuapp.com', 'localhost', '127.0.0.1', 'localhost:8000'] INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'django_comments', 'shops', 'django.contrib.gis' ] SITE_ID = 1 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 = 'django_project3.urls' … -
DRF nested serializer
im using django rest framework to build apis . i have 2 classes related with onToOne relationship and i want to serialize data of the annonce_demande class , and create a post method in my endpoint , but i got problems with the nested serializer (fiche_annonce class). i think the problem is in the create method of the serializer. plz help me and thanks. class fiche_annonce(models.Model): ville_distination = models.CharField(max_length=50) lieu_depart = models.CharField(max_length=50) lieu_arrive = models.CharField(max_length=50) date_depart = models.DateTimeField(max_length=50,) date_arrive = models.DateTimeField(max_length=50) is_accepted = False visiblty = False class annonce(models.Model): compte = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) num_tele = models.IntegerField() ville = models.CharField(max_length=30) bagages = models.CharField(max_length=12, choices=[x.value for x in type_bagages]) comment = models.TextField(max_length=200) fiche = models.OneToOneField(fiche_annonce, on_delete=models.CASCADE) visiblty = False created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Ad_Serializer(serializers.ModelSerializer): fiche = fiche_Serializer() compte = serializers.PrimaryKeyRelatedField(queryset=user.objects.all().filter(is_active=True), read_only=False, required=False, default=None, allow_null=True) class Meta: model = annonce_demande fields = ['compte', 'num_tele', 'ville', 'bagages', 'comment', 'fiche', 'visiblty', 'get_created_time', 'get_updated_time' ] #def create(self, validated_data): # return annonce_demande.objects.create(**validated_data) #def validate_compte(self, val): # return self.context['request'].user def create(self, validated_data): print(validated_data) fiche_data = validated_data.pop('fiche') #print("---") #print(fiche_data) #print("---") print(validated_data) ad = annonce_demande.objects.create(**validated_data) print(ad) fiche_annonce.objects.create(**fiche_data) return ad class UserLoginView(APIView): #queryset = user.objects.all() permission_classes = [AllowAny] serializer_class = UserLoginSerializer #lookup_field = 'id' def post(self, request): serializer … -
Django Insert User_id as foreignKey in Post entry
I'm trying to save the user_id as a foreign key as the user publishes a new post. In a lot of other articles a suggested solution is: user= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) If I do that, I get: IntegrityError at /createPost/Error: NULL-Value in column »user_id« verletzt Not-Null-ConstraintDETAIL: Failed line contains (13, hhjkjh, hjkhkjhkj, https://www.google.de, 2020-06-06, hhjkjh, null). But the user is logged in. # my models.py from django.db import models from django.conf import settings from django.utils import timezone from slugify import slugify from django.contrib.auth.models import User class UserEntry(models.Model): user= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title= models.CharField(max_length=500) content= models.TextField() link = models.URLField(max_length=200) date_published= models.DateField(default=timezone.now) url= models.SlugField(max_length=500, unique=True, blank=True, editable=False) def save(self, *args, **kwargs): self.url= slugify(self.title) super(UserEntry, self).save(*args, **kwargs) #my forms.py class UserEntryForm(forms.ModelForm): class Meta: model= UserEntry fields= ["title", "content", "link"] #my views.py def userposts_create_view(request): form= UserEntryForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return HttpResponseRedirect("/") context= {'form': form, } return render(request, '../templates/userposts-create-view.html', context) #and my html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% if user.is_authenticated %} <p>Welcome, {{ user.username }}. Thanks for logging in.</p> <p>Go to your page <a href="{{user.username}}">here</a></p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %} <form enctype="multipart/form-data" method="POST" action=""> …