Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Are forms necessary for Django authentication?
I'm new to Django and I'm working on a project which will be using APIs with Django REST framework. And working on it, creating the authentication using DjangoDoc AUTH, I was wondering if it was necessary to use these forms, are there any other authentication or validation methods? I took a look at these articles: DjangoDoc Quora Django Tutorial But I can't see if they're really necessary or if there is another way. Thanks for your responses! -
How to concatenate list of query sets in django models
I have list of query sets and need to connect them into one. How to concatenate list of query sets into one? class TagListAPIView(generics.ListAPIView): serializer_class = serializers.TagSerializer def get_queryset(self): search_words = self.request.query_params['search_with'].split() querysets = [] for word in search_words: queryset = Tag.objects.filter( Q(name__contains = word) ) querysets.append(queryset) return querysets # ListAPIView does not accept this -
Multiple Files In Email Django
I have a list of files, each with its own checkbox. I then get a list of all of the items where the checkbox is marked. I would like for these files to be passed to my view and to be automatically attached. Here is the view which shows the list of files: def DocListView(request, pk): if request.method == "POST": documents = request.POST.getlist('checks') else: return render(request, 'doc_list.html', context) doc_list.html <div> <ul class="list-group"> {% for item in PackingListDocs %} <li class="list-group-item"> <a href="{% url 'EditPackingListView' item.Packing_List.pk %}" class="a" type="button"> <div class="md-v-line"></div><input type="checkbox" name="checks" value="{{ item.PackingListDocument.url|default_if_none:'#' }}">{{item.Packing_List.Name}}<a class="doclink" href="{{ item.PackingListDocument.url|default_if_none:'#' }}" download>View Doc</a> </a> </li> {% endfor %} </ul> </div> So as you can see I get a list ```documents = request.POST.getlist('checks'). Now my next view currently looks like this. def email(request): if request.method == "POST": form = EmailForm(request.POST,request.FILES) if form.is_valid(): post = form.save(commit=False) # post.published_date = timezone.now() post.save() email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') document = request.FILES.get('document') email_from = settings.EMAIL_HOST_USER recipient_list = [email] email = EmailMessage(subject,message,email_from,recipient_list) base_dir = 'media' email.attach_file('Poseidon/media/media/'+str(document)) email.send() return redirect('HomeView') else: form = EmailForm() return render(request, 'docemail.html', {'form': form}) It works fine, but it makes the user choose a file to upload, and I can … -
Django submit button not working on Ajax request
I am building a website which users can create posts and comment on it, however, after clicking the submit button in the post_detail.html template to submit the comment, nothing happens and I cannot een see an error. I am using jQuery to submit the form this is my post_detail view: @login_required def post_detail(request, id): data = dict() post = get_object_or_404(Post, id=id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(False) comment.post = post comment.name = request.user comment.save() comments = post.comments.all() data['form_is_valid'] = True data['comments'] = render_to_string('home/posts/post_detail.html', { 'comments':comments }, request=request) else: data['form_is_valid'] = False else: form = CommentForm comments = post.comments.all() context = { 'form': form, 'comments': comments, 'post': post } data['html_data'] = render_to_string('home/posts/post_detail.html', context,request=request) return JsonResponse(data) this is my post_detail.html template: {% load crispy_forms_tags %} {% load static %} <script src="{% static 'js/comment.js' %}"></script> <div class="modal-header-sm"> <button type="button" class="close mx-2" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="card mt-3 rounded-0 mb-3" style="max-width: 100rem !important;"> <div class="card-body text-dark"> <div class="d-flex"> <img class="img-create-post rounded-circle mr-2" style="width: 50px;height: 50px;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg" alt="Profile image"> <span class="align-text-top"><a class="mr-2 text-dark font-weight-bolder" href="#">{{ post.author.first_name }} {{ post.author.last_name }} </a><br><p class="font-weight-light text-muted">{{ post.title }}</p></span> <div class="float-right text-right ml-auto"> <p class="text-muted small" style="font-size: 0.7rem;">{{ post.date_posted|date:"F d, … -
Subtracting from a IntegerField field in django
I am a medical technologist trying to build a inventory program for my laboratory. My goal is to have a table that shows all of the reagent we have in a particular section of the lab and then display it to the user. I have been able to accomplish this by using django-tables2. What I would like to do next is have a form that allows the user to select the reagent they take out, then the quantity of which they took out, submit the form and then have whatever quantity they took be subtracted from the total reagent count of that particular reagent. Here is what I have so far. Any help is appreciated! forms.py from django import forms class ReagentCheckoutForm(forms.ModelForm): reagent_name= forms.CharField() amount_taken= forms.IntegerField() models.py class Inventory(models.Model): reagent_name= models.CharField(max_length=30) reagent_quantity= models.IntegerField() views.py def reagent_checkout(request): if request.method == 'POST': form= ReagentCheckoutForm(request.POST) if form.is_valid(): form.save() reagent_name= form.cleaned_data['reagent_name'] amount_taken= form.cleaned_data['amount_taken'] -
Django 1.11 to 2.2 with jQuery
I have working application in Django 1.11. It has a few forms and filters that use jQuery, bootstrap, select2, all included in a scripts block in a base.html file. When I upgrade to Django 2.2, one of the forms stops working with a "Uncaught TypeError: $(...).select2 is not a function" error in the (browser) console. Moving jQuery, bootstrap, and select2 from the to the in base.html resolves this, but causes a different form to stop working with a "Uncaught TypeError: $(...).select2 is not a function" error in the (browser) console. Where should I be looking to debug this issue? What could have changed from 1.11 to 2.2 to cause the first error? -
Getting errorTemplate DoesNotExist while adding new page using new class (wagtail, django)
The problem is that when creating a page using the new class, I get a TemplateDoesNotExist error. Full error text: TemplateDoesNotExist at /green-tea/ home/product.html Request Method: GET Request URL: http://relizerel.pythonanywhere.com/green-tea/ Django Version: 3.0.4 Exception Type: TemplateDoesNotExist Exception Value: home/product.html Exception Location: /home/relizerel/.virtualenvs/env/lib/python3.8/site-packages/django/template/loader.py in get_template, line 19 Python Executable: /usr/local/bin/uwsgi Python Version: 3.8.0 Python Path: ['/home/relizerel/myshopwt', '/var/www', '.', '', '/var/www', '/home/relizerel/.virtualenvs/env/lib/python38.zip', '/home/relizerel/.virtualenvs/env/lib/python3.8', '/home/relizerel/.virtualenvs/env/lib/python3.8/lib-dynload', '/usr/lib/python3.8', '/home/relizerel/.virtualenvs/env/lib/python3.8/site-packages'] Server time: Вт, 31 Мар 2020 02:25:43 +0200 My model.py file: from django.db import models from modelcluster.fields import ParentalKey from wagtail.core.models import Page, Orderable from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel, InlinePanel from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.contrib.settings.models import BaseSetting, register_setting class HomePage(Page): pass class Product(Page): sku = models.CharField(max_length=255) short_description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=10) image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) content_panels = Page.content_panels + [ FieldPanel('sku'), FieldPanel('price'), ImageChooserPanel('image'), FieldPanel('short_description'), InlinePanel('custom_fields', label='Custom fields'), ] class ProductCustomField(Orderable): product = ParentalKey(Product, on_delete=models.CASCADE, related_name='custom_fields') name = models.CharField(max_length=255) options = models.CharField(max_length=500, null=True, blank=True) panels = [ FieldPanel('name'), FieldPanel('options'), ] @register_setting class MushkinoSettings(BaseSetting): api_key = models.CharField( max_length=255, help_text='Ваш публичный ключ API Мушкино' ) My base.py (settings.py) file: import os PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # Application … -
I have error message " for file changes with StatReloader Exception in thread django-main-thread:"
I have errors in configuration, and when I had been downloading the project from Github that error shown to me when I run the server that problem happened also I tried to create a new project, so the project run. How can I avoid this problem and solve it? Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mediumeditor' Traceback (most recent call last): File "C:/xampp/htdocs/athar/manage.py", line 21, in <module> main() File "C:/xampp/htdocs/athar/manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 599, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) … -
Sending users a password insertion Django Rest Framework
I am using Django Rest Framework and want to be able to send a user a password reset view. It actually comes from a user inviting them into the software but it automatically sets a secure password. I want to be able to send that user an email asking them to change their password. How can I go about this? -
Creating tcp connection to Redis infinite (django, celery, channels)
I'm using Django with Channels 2 and create task With Celery, but when I pass the results of the job to async_to_sync (channel_layer.group_send) ( 'view', {'type': 'view.joke', 'text': joke} ) and look with debug, see the following. [2020-03-31 02:41:09,601: DEBUG/MainProcess] Using selector: SelectSelector [2020-03-31 02:41:09,602: DEBUG/MainProcess] Creating tcp connection to ('127.0.0.1', '6379') At the same time, the task is in progress every 15 seconds, and its result should be displayed on the page, but i have printed the first result, and then Celery freezes. -
Django Migration InternalError 1054 Unknown column
I added an ImageField to an existing item in models.py, I ran makeMigrations and Migrate and yet as a result now if I go to my admin panel I get the below error: InternalError(1054, u"Unknown column 'modelname.picture' in 'field list'") This error goes away if I remove that ImageField. I'm running Django==1.11.26 This is a copy of the feild: picture = models.ImageField(null=True, blank=True, upload_to='images/') Very appreciative of any help on this one. -
Why in javaScript, mySQL timestamp are not converted the same on mobile then on desktop?
I have a ajax request to fetch django data in json. i receive the response and everything is ok, i keep dateTime in my django app as naive date since i don't have to manage timezone. i want date/time to be showed like they are saved. Ok in my javascript, when i do a: console.log(item.fields.timeStamp); I receive: 2020-03-29T21:00:00.143 On both desktop and my iPhone, and that is wath i expect, but when i do that: alert(new Date(item.fields.timeStamp)); I receive: Sun Mar 29 2020 20:05:21 GMT-0400 (heure d’été de l’Est) On my desktop and: Sun Mar 29 2020 16:05:21 GMS-0400 (EDT) And that is totally wrong!! So all timeStamp in my app are totally off on mobile devices. What can be my problem ? -
Handling nested object representations in Django REST Framework
I have some problem with handling nested serializers (DRF). I want to collect data with some structure like this: { 'datetime': xxxxxxx, 'measurements': [ {'int_test': 1, 'char_test': '1'}, {'int_test': 2, ''char_test: '2'} ] } I'm using the documentation (https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects) and i'm looking at (https://medium.com/@raaj.akshar/creating-reverse-related-objects-with-django-rest-framework-b1952ddff1c) and still have the HTTP 400 response: '{"measurements":["This field is required."]}' (201 only when measurement is read_only - it's Logical) models.py class Data(models.Model): datetime = models.DateTimeField() def __str__(self): return 'just testing' class Measurement(models.Model): data = models.ForeignKey(Data, on_delete=models.CASCADE) char_test = models.CharField(max_length=100) test = models.IntegerField(default=0) def __str__(self): return self.char_test serializers.py: class MeasurementSerializer(serializers.ModelSerializer): class Meta: model = Measurement fields = '__all__' class DataSerializer(serializers.ModelSerializer): measurements = MeasurementSerializer(many=True) class Meta: model = Data fields = ['datetime', 'measurements'] def create(self, validated_data): measurement_validated_data = validated_data.pop('measurements') data = Data.objects.create(**validated_data) Measurement.objects.create(data=data, **measurement_validated_data) return data And my simple post request: data = { "datetime": datetime.now(), "measurements": [ {'test': 1, 'char_test': '1'}, {'test': 2, 'char_test': '2'}, ], } r = requests.post( 'http://127.0.0.1:8000/api/', data=data, ) Did I forget something? -
400 Bad Request - django template
I'm trying to add possibility to add product to cart from two places in my Django project. Index view (main page, non-API version in main views file) - in this view this works. This view is in main project view.py file. def index(request): products = Product.objects.all()[:10] products_dict = {'products': products} return render(request, 'products/index.html', products_dict) Template index.html and no problem to redirect to add_item_to_cart view (from application Cart) {% for item in products %} <a href="{% url 'cart:add_item_to_cart' item.id %}" class="btn essence-btn">Add to Cart</a> {% endfor %} Product detail class view (API version in Product application) - in this view this doesn't work class ProductDetail(ListCreateAPIView): template_name = 'products/product_api.html' renderer_classes = [TemplateHTMLRenderer] serializer_class = ProductSerializer def get(self, request, pk): product = get_object_or_404(Product, pk=pk) serializer = ProductSerializer(product) return Response({'serializer': serializer, 'object': product}) Template product_api.html and problem to redirect to add_item_to_cart view. I have receive 400 Bad Request {% for item in products %} <a href="{% url 'cart:add_item_to_cart' object.id %}">Add to Cart</a> {% endfor %} Why the same resource works to first template but doesn't to second? Is it possible to redirect from API view to different app (Cart)? I was able to handle POST request by adding post method and to redirect to … -
{% load static%} {% block content %} {%endblock%} arent being executed properly in my website
{% extends 'budget/base.html' %} {% block content %} <div class="container"> <h1>My Projects</h1> <hr> <div class="row"> {% for project in project_list %} <div class="col s12 md6 xl3"> <div class="card-panel"> <h5>{{ project.name }}</h5> <a href="{% url 'detail' project.slug %}" class="btn">Visit</a> </div> </div> {% empty %} <div class="noproject-wrapper center"> <h3 class="grey-text">Sorry, you don't have any projects, yet.</h3> <a href="{% url 'add' %}" class="btn-large grey"> <i class="material-icons white-text left">add_circle</i> <span class="bold">Add Projects</span> </a> </div> {% endfor %} </div> </div> {% endblock %} if you open the webpage with this it doesn't display what it's supposed to display I checked the code and I don't know what's wrong -
How do i convert WSGIRequest to string
if i pass a parameter to graph_data() and convert it into string in 1st pass of program execution it take a parameter as a string but in 2nd pass it will take parameter as please someone help me in it i want to return a proper graph for graph_data() Note:- if i manually pass String(Stock Name) to web.dataReader() it will return graph, index.html:-Here i want to show graph <img src="{% url "showplt" %}" /> views.py:- import pandas_datareader as web def index(request): if request.method == 'POST': search = request.POST['search'] graph_data(search) def graph_data(request): request_p = str(request) ex = '.NS' st_name = request_p + ex print('STNAME:', st_name) print(type(st_name)) print(type(request_p)) print(type(ex)) df = web.DataReader(st_name, data_source='yahoo', start='2019-01-01', end='2020-03-16') print(df) plt.figure(figsize=(12, 7)) plt.title('Close Price History') plt.plot(df['Close']) plt.xlabel('Date', fontsize=18) plt.ylabel('Close Price in RS', fontsize=18) buffer = io.BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pil_image = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pil_image.save(buffer, "PNG") pylab.close() response = HttpResponse(buffer.getvalue(), content_type="image/png") return response urls.py:- path('showplt/', views.graph_data, name='showplt'), error(Terminal):- STNAME: <WSGIRequest: GET '/showplt/'>.NS <class 'str'> <class 'str'> <class 'str'> Not Found: /searchicon.png STNAME: RELIANCE.NS <class 'str'> <class 'str'> <class 'str'> Internal Server Error: /showplt/ Traceback (most recent call last): -
issue with html display in Django maybe coming from view.py structure
I am building a django app and i am very not familiar with the frontend stuff. Ultimately i want to build a dashboard but as now I am somewhat struggling with building a view that matches what I want it to display. So far the view class is well transfered to frontend (no error when running the server), but instead of displaying values, it displays black dots. here is attached my html code as well as my view.py <ul> {% for reference in top_sellers_list %} <li><a href="/dashboard/{{ top_sellers_list.reference }}/"> {{top_sellers_list.avg_per_week }}</a></li> {% endfor %} </ul> <ul> {% for reference in classification %} <li><a href="/dashboard/{{ classification.Class }}/"> {{classification.inventory_dollars }}</a></li> {% endfor %} </ul> <ul> {% for reference in anormal %} <li><a href="/dashboard/{{ anormal.reference_anormales }}/"></a></li> {% endfor %} </ul> <ul> {% for reference in negat %} <li><a href="/dashboard/{{ negat.reference_negatives }}/"></a></li> {% endfor %} </ul> <ul> {% for reference in service %} <li><a href="/dashboard/{{ service.reference_service }}/"></a></li> {% endfor %} </ul> from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from .models import top_sellers, Classification, stock_anormal, stock_negatif, niveau_service # Create your views here. def dashboard(request): top_sellers_list = top_sellers.objects.order_by('avg_per_week')[:8] classification = Classification.objects.order_by('Class') anormal = stock_anormal.objects.order_by('reference_anormales') negat = stock_negatif.objects.order_by('reference_negatives') service = niveau_service.objects.order_by('reference_service') context1 = { … -
Accessing Django 3 TextChoices via an exposed API endpoint?
I am using Django 3.0.4 with Django REST Framework 3.11.0 where I have a models.py like: from django.db import models from model_utils.models import TimeStampedModel class SampleModel(TimeStampedModel): class Options(models.TextChoices): FOO = "A" BAR = "B" BAZ = "C" name = models.CharField(default="", max_length=512) options = models.CharField( max_length=2, choices=Options.choices, default=Options.FOO ) I would like to be able to create an API endpoint to return a list of my TextChoices as a tuple. I have a React frontend where I want to create a <select> dropdown with my list of choices. If I can access the list of TextChoices via an API endpoint, I should be good to go. path("api/sample/choices/", views.SampleChoicesListView.as_view(), name="sample_choices") I'm not sure what my views.py needs to look like to make this work... class SampleChoicesListView(generics.ListAPIView): pass -
Django: UNIQUE constraint failed: user.username
I have a problem using Djangos Default user from django.contrib.auth.models but trying to use it with my custom User model, using from django.contrib.auth.models import AbstractUser. So here is my User model: from django.db import models from django.contrib.auth.models import AbstractUser, UserManager as AbstractUserManager # from django.conf import settings from django_countries.fields import CountryField # https://github.com/SmileyChris/django-countries from django.db.models.signals import post_save from django.dispatch import receiver class UserManager(AbstractUserManager): pass class User(AbstractUser): """auth/login-related fields""" is_a = models.BooleanField('a status', default=False) is_o = models.BooleanField('o status', default=False) def __str__(self): return "{} {}".format(self.first_name, self.last_name) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: User.objects.set_password(instance.password) and here is my Profile model: from django.db import models from django_countries.fields import CountryField # https://github.com/SmileyChris/django-countries from django.contrib.auth import get_user_model User = get_user_model() # https://medium.com/swlh/best-practices-for-starting-a-django-project-with-the-right-user-model-290a09452b88 from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): """non-auth-related/cosmetic fields""" user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='Profile') birth_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) nationality = CountryField(null=True) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) def __str__(self): return f'{self.user.username} Profile' """receivers to add a Profile for newly created users""" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() But before adding User.objects.set_password(instance.password) to my User model, I did it in … -
How do I get an element that is nested within a JSON dictionary?
I got a JSON response using the Spotify API and I'm trying to access the element called 'name' (one says '3 Doors Down' and the other starts with 'Bret Michaels') that seems to be inside the 'items' element but I can't seem to find the solution. This is how I loaded the data: search_results = requests.get(search_url + 'q=' + query + '&type=artist', headers=granted_headers).json() Here is my JSON data: { 'artists': { 'href': 'https://api.spotify.com/v1/search?query=3+doors+down&type=artist&offset=0&limit=20', 'items': [ { 'external_urls': { 'spotify': 'https://open.spotify.com/artist/2RTUTCvo6onsAnheUk3aL9' }, 'followers': { 'href': None, 'total': 2631330 }, 'genres': [ 'alternative metal', 'nu metal', 'pop rock', 'post-grunge' ], 'href': 'https://api.spotify.com/v1/artists/2RTUTCvo6onsAnheUk3aL9', 'id': '2RTUTCvo6onsAnheUk3aL9', 'images': [ { 'height': 640, 'url': 'https://i.scdn.co/image/ead4e883a59d30d8c157385aa531d3fe8e688fc0', 'width': 640 }, { 'height': 320, 'url': 'https://i.scdn.co/image/611a4fd8aaf2637c5894acf65f12e79d75926329', 'width': 320 }, { 'height': 160, 'url': 'https://i.scdn.co/image/f1a1a2c37f2f6d242b1ab7ae3f4d893bf5822095', 'width': 160 } ], 'name': '3 Doors Down', 'popularity': 72, 'type': 'artist', 'uri': 'spotify:artist:2RTUTCvo6onsAnheUk3aL9' }, { 'external_urls': { 'spotify': 'https://open.spotify.com/artist/2kPbQDZvnasPcCuXbq6YQx' }, 'followers': { 'href': None, 'total': 156 }, 'genres': [ ], 'href': 'https://api.spotify.com/v1/artists/2kPbQDZvnasPcCuXbq6YQx', 'id': '2kPbQDZvnasPcCuXbq6YQx', 'images': [ ], 'name': 'Bret Michaels (Featuring Brad Arnold of 3 Doors Down, Chris Cagle, Mark Wills)', 'popularity': 4, 'type': 'artist', 'uri': 'spotify:artist:2kPbQDZvnasPcCuXbq6YQx' } ], 'limit': 20, 'next': None, 'offset': 0, 'previous': None, 'total': 4 } } -
Are There OS Difference Concerns Running a Docker Container on Different Operation Systems
I want to migrate a Django project into a Docker container (hoping I have the right term here) so that I can more closely mimic my integration and productions environments. I'm developing the django project on MacOS and my integration server is Ubuntu 18.04 in a droplet on Digital Ocean. I already got bit by forgetting about letter case sensitivity running directly on MacOS. From other questions and answers I've read here, that the container doesn't have its own OS, but relies on the host. Is it possible then to make a Docker container on MacOS behave as if it is running Ubuntu 18.04? For example, will running in a Docker container error out on letter case issue where MacOS won't? IIRC, all linux versions are case sensitive. What about differences between various flavors of Linux? If differences are a concern, can I specify Ubuntu for my container in some fashion? -
How to apply function to field in values_list lookup
My line of code goes: replies = Comment.objects.filter(reply_to__pk__exact=pk).annotate(dates=timesince.timesince('date'))\ .order_by('-dates')\ .values_list("owner__username", "text", "dates", "likes", "owner__customuser__picture") I want the dates column in the result to be transformed by the timesince.timesince function. Instead, it throws an error like so: AttributeError: 'str' object has no attribute 'year' How do I resolve this? -
django: ValidationError with UniqueConstraint on Model.Forms, clean()
I want to get a message (ValidationError) on the form insted the of page with IntegretyError, from the UniqueConstraint. models.py class Solicitacao(models.Model): '''Modelo de solicitação''' solicitante = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, validators=[]) disciplina = models.ForeignKey("Disciplina", on_delete=models.CASCADE, validators=[]) [..some other data...] data_solicitacao = models.DateTimeField( ("Data da solicitação"), auto_now_add=True) class Meta: ordering = ['-data_solicitacao', 'solicitante'] constraints = [ models.UniqueConstraint(fields=['solicitante', 'disciplina'], name='unique_solicitação') ] views.py @login_required def nova_solicitacao(request): if request.method == 'POST': form = SolicitacaoForm(request.user, request.POST) form.instance.solicitante = request.user if form.is_valid(): solicitacao = form.save(commit=False) solicitacao.save() return redirect(reverse_lazy('cc:solicitacoes')) else: form = SolicitacaoForm(request.user) return render(request, 'cc/solicitacao_form.html', {'form': form}) forms.py class SolicitacaoForm(forms.ModelForm): class Meta(): model = Solicitacao fields = ['disciplina', 'justificativa', 'documentos'] def __init__(self, user, *args, **kwargs): super(SolicitacaoForm, self).__init__(*args, **kwargs) if not user.is_staff: curso = user.curso self.fields['disciplina'].queryset = Disciplina.objects.filter(curso=curso) I belive the best approuch would be to writr def clean() but since solicitante isn't one of the fields on the form i couldn't figure how to acess in clean. I also plan to limit to 3 anwsers per user. I plan to use a query basead on the user in the clean field, bu again i couldn't figure how to access it. -
UNIQUE constraint failed or NOT NULL constraint failed - no inbetween
I am working on a project where a user initially registers, then fills in two separate pages of information about their profile ( on the PII and finalPII pages). For whatever reason I have not been able to save this information correctly into my Profile model and always get one of two errors that have to do with the user id: either a UNIQUE constraint failed when I include the line profile.user = request.useror a NOT NULL constraint failed error when I get rid of this line. I am not sure where the middle ground is here and I greatly appreciate any help or advice given. views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm, PIIForm, FinalPIIForm from .models import Profile def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return … -
Django model is not saving to Database
I have a very simple model containing just four fields: meeting_date,meeting_hour, participant_name and ```participant_email``. I'm sending email about selected data, hour to participant, it works. But this schedule is not writing to database. Here are my codes: views.py: def index(request): context = { 'schedules': Schedule.objects.all() } participant_name = request.POST.get('name') participant_email = request.POST.get('email') meeting_date = request.POST.get('date') meeting_hour = request.POST.get('hour') subject = 'Görüş' message = 'Hello ' + str(participant_name) + '. \nDate: ' + str(meeting_date) + ' hour ' + str(meeting_hour). from_email = settings.SERVER_EMAIL recipient_list = [participant_email] send_mail(subject, message, from_email, recipient_list) if request.POST.get('participant_email'): Schedule.objects.create( participant_name = request.POST.get('name'), participant_email = request.POST.get('email'), meeting_date = request.POST.get('date'), meeting_hour = request.POST.get('hour') ) return render(request, 'index.html', context) admin.py: class ScheduleAdmin(admin.ModelAdmin): list_display = ['participant_name', 'participant_email', 'is_scheduled', 'meeting_date', 'meeting_hour'] admin.site.register(Schedule, ScheduleAdmin) models.py: class Schedule(models.Model): participiant_name = models.CharField(max_length=100) participiant_email = models.CharField(max_length=100) meeting_date = models.DateField() meeting_hour = models.TimeField() is_scheduled = models.BooleanField(default=False) def __str__(self): return self.meeting_date html: <form action="{% url 'index' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label><br/> <input type="text" name="name" id="name" placeholder="Name"> </div> <div class="form-group"> <label for="email">Email</label><br/> <input type="email" name="email" id="email" placeholder="Email"> </div> <div class="form-group"> <label for="date">Date</label><br/> <input type="date" name="date"> </div> <div class="form-group"> <label for="hour">Saat</label><br/> <select name="hour" id="hour"> <option value="1">Hour</option> <option value="14:00">14:00</option> <option value="15:00">15:00</option> <option value="16:00">16:00</option> <option value="17:00">17:00</option> <option value="18:00">18:00</option> …