Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to setup Amazon AWS S3 static in Django
I'm trying to setup amazon AWS S3 static Here is my settings.py USE_S3 = os.getenv('USE_S3') == 'TRUE' if USE_S3: # aws settings AWS_ACCESS_KEY_ID = 'AKIAVYBTPX6PETRM7GXR' AWS_SECRET_ACCESS_KEY = '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' AWS_STORAGE_BUCKET_NAME = 'manual.la' AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') I've uploaded my css files to my bucket. And it's available with HTTP: http://manual.la.s3.amazonaws.com/static/css/bootstrap.min.css But when I use the link with HTTPS - it gives a warning: https://manual.la.s3.amazonaws.com/static/css/bootstrap.min.css Here is my html: {% load static %} <html> <head> <link href="{% static 'css/bootstrap.min.css' %}" rel='stylesheet'> </head> Can anyone help me with this? Thank you -
MySQL 5.7+ is required to use JSONField
I was initialising my django project to pythonanywhere.com but while i was migrating i saw this error. (django_mysql.E016) MySQL 5.7+ is required to use JSONField HINT: At least one of your DB connections should be to MySQL 5.7+ I am using JSONField in my models. Can anyone suggest me a fix? Settings.py 'default' :{ 'ENGINE': 'django.db.backends.mysql', 'NAME': '******', 'USER': '****', 'PASSWORD': '*****', 'HOST': '******', 'PORT': '3306', 'OPTIONS': { # Tell MySQLdb to connect with 'utf8mb4' character set 'charset': 'utf8mb4', }, }, -
How to extract JSON value from a list and render it in a django model form?
I am trying to render a Django model form using the below model. The problem is one of the model field is a JSONField. This is a list of length 1 having some JSON data. When I render the model form, the number field renders the list without any issues. But I want to extract the phone value from the JSON inside the list and render it. I have tried extracting it in the template but it is not working as intended. How can I extract the phone value from the JSON and render it in the form? As example, when I render the data for id 1 using my view, I should see 'Client_1' in the name field and '1234567890' in the number field. I am using Django 3.1 and using Django Crispy Forms to render the model form. Data as seen client table in db: id name number 1 Client_1 [{'type': 'mobile', 'phone': '1234567890'}] 2 Client_2 [{'type': 'mobile', 'phone': '3334445555'}] 3 Client_3 [{'type': 'mobile', 'phone': '9876543210'}] models.py: class Client(models.Model): name = models.TextField() number = models.JSONField(blank=True, null=True) forms.py: from .models import Client class ClientForm(forms.ModelForm): class Meta: model = Client fields = '__all__' clients.html template: {% load crispy_forms_tags %} <form … -
Django order by multipe elements
I'm trying to achieve the following with a Django query: { "channel_x":{ "date_x":{ "pl__sum":1 }, "date_y":{ "pl__sum":2 } }, "channel_y":{ "date_x":{ "pl__sum":1 }, "date_y":{ "pl__sum":2 } } } I wrote the following code in an attempt to do so: Tip.objects.values("channel__name", "prediction__fixture__date").filter(prediction__fixture__date__date__lte=datetime.now(), prediction__fixture__date__date__gte=datetime.now()-timedelta(days=6)).order_by('channel__name', 'prediction__fixture__date').annotate(Sum('pl')) But this returns this {'channel__name': 'SB Betting (Live)', 'pl__sum': Decimal('7.730')}, {'channel__name': 'SB Betting (Live)', 'pl__sum': Decimal('-8.460')} How can I achieve the same (or similar) as my example above? -
duplicate key error primary key django and mongo (djongo)
i have some data in my model Paper with id primary key from id = 1 - 30 id field created by django but now when i create new object it want to created with id = 1 then raise a duplicate error i dont have any idea can anybody help me ? -
How can I Build an Django REST API that will judge C, C++, Java and Python codes and return verdict, runtime, memory-used?
I want to build a Django Rest API as a part of my ongoing project, which is mainly an Online Judge. I want to send user-submitted-code, input-file, memory-limit, time-limit, language-type and the API will return me the verdict, memory-used, runtime. Is it possible with Django REST API? If possible, how can I build one? -
Django 2.2 'SafeText' object has no attribute 'get'
I am using Django 2.2 in a project. I am rolling an extra lightweight app that allows users to modify the raw HTML used in a template. This is a cut down example of the function I have written to do that: def show_page(request): from django.template import Context, Template template = Template("<h3>My name is {{ my_name }}.</h3>") context = Context({"my_name": "Adrian"}) return template.render(context) # <- Django barfs at this line I get the exception shown in the title: AttributeError at /show-page 'SafeText' object has no attribute 'get' How do I resolve this error, so I can display the page correctly? -
Create object foreignkey relation
so I have these two models class Recipe(models.Model): short_description = HTMLField(max_length=400) likes = models.ManyToManyField(User, blank=True, related_name='recipe_likes') slug = models.SlugField(blank=True, unique=True) published_date = models.DateTimeField(blank=True, default=datetime.now) ratings = GenericRelation(Rating, related_query_name='recipes') class Ingredient(models.Model): name = models.CharField(max_length=20) amount = models.FloatField() recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='recipe_ingredients') In the admin panel from the recipes section I want to be able to add ingredients for that recipe, what do I need? I think I don't know the right searchterms to use, hope you understand what I mean. Thanks for the help. -
Adding Validation for case insensitivity in Django python
Hi i am learning django Python. In my modals i have added a button which will upload csv file. I have added validation that a csv file must have summary and Test case ID. But i want to know that how to add validation that while uploading csv file uppercase and lower case both should work. I am having error if the s in summary is 'S' i.e in capitals it shows 'CSV file must have "summary" column and "Issue Key" column') but insted it should upload csv file. Modals.py class AICSVFile(models.Model): file = models.FileField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Form.py class CsvUpload(forms.Form): csv_file = forms.FileField() def clean_csv_file(self): value = self.cleaned_data['csv_file'] if not value.name.endswith('.csv'): raise forms.ValidationError('Invalid file type') # Read data from file 'filename.csv' # (in the same directory that your python process is based) # print(dir(value)) # with open(value.file, 'r') as csvfile: try: data = pd.read_csv(value.file, encoding = "ISO-8859-1") # Do whatever checks you want here # Raise ValidationError if checks fail except Exception as e: print('Error while parsing CSV file=> %s', e) raise forms.ValidationError('Failed to parse the CSV file') if 'summary' not in data or 'Test Case ID' not in data: raise forms.ValidationError( 'CSV file must have … -
how to post data to table having foreignkey relation with user model using django rest api
i would like to add data to table which having a foreignkey relatonship with user model through django rest api. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): # username = None email = models.EmailField(verbose_name='email',max_length=50,unique=True) phone = models.CharField(max_length=17,blank=True) REQUIRED_FIELDS = [ 'first_name', 'last_name', 'phone', 'username', ] USERNAME_FIELD = 'email' def get_username(self): return self.email class UserInfo(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) address = models.CharField(max_length=50) zipcode = models.CharField(max_length=20) medication = models.CharField(max_length=25) def __str__(self): return str(self.user) serializers.py from djoser.serializers import UserCreateSerializer class UserCreateSerializerCustom(UserCreateSerializer): class Meta(UserCreateSerializer.Meta,): model = User fields = ( 'id', 'email', 'username', 'password', 'first_name', 'last_name', 'phone', ) ## User Additional Info Serializers class UserAdditionalSerializers(serializers.ModelSerializer): user = UserCreateSerializerCustom() class Meta: model = UserInfo fields = ( 'user', 'address', 'zipcode', 'medication', ) views.py class UserAdditionalView(generics.ListCreateAPIView): queryset = UserInfo.objects.all() serializer_class = UserAdditionalSerializers how will i send user instance with the data....?? i'm using token authentication for the api. Which is the best way to achieve this..?? -
Reverse for 'cart_detail' not found. 'cart_detail' is not a valid view function or pattern name
Here is my Add to Cart button HTML:` <a href="{% url 'store:add_cart' product_detail.id %}"> </a> Here is my add_cart view: def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id=_cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product=product, quantity=1, cart=cart, ) cart_item.save() return redirect('cart_detail') And here's my urls.py for add_cart and cart_detail: app_name = 'store' urlpatterns = [ path('', views.home, name='home'), path('product-list/', views.product_list, name='product_list'), path('cart/', views.cart_detail, name='cart_detail'), path('cart/add/<int:product_id>', views.add_cart, name='add_cart'), path('detail/<slug:product_slug>', views.product_detail, name='product_detail'), path('category/<slug:category_slug>', views.home, name='products_by_category'), ] When I click on add to cart button in my product-detail page: I GET THIS ERROR: Reverse for 'cart_detail' not found. 'cart_detail' is not a valid view function or pattern name. Which points to my view add_property -> return redirect('cart_detail') I tried changing my 'cart_detail' to '/cart' in the views but then it's showing that my cart has no items even though the model objects Cart and Cart Item are created. PLEASE HELP RESOLVE ASAPenter image description hereenter image description here -
Django on Google App Engine Flexible: create and remove files
I have a Django application deployed on Google App Engine (flexible environment). Can I create files and remove files like this: with open('myfile.xls', 'w') as file_object: #writing to file os.remove('myfile.xls') or use NamedTemporaryFile? Now this code works, but after some days after deploying my app become running slowly. It is not about cold start. Redeploying fixes it. Сan files not be deleted and waste disk space? Or there is another reason? -
Stripe Error: As per Indian regulations, export transactions require Customer's address, but i am selling digital prints
I am building an app with React and DRF to sell digital prints (Jpeg, png, psd). I am using stripe as payment gateway and I am getting this error. If I am selling digital product than there is no need to ask for Customer's address. I am not exporting anything. The idea is to charge customer for a print than provide a downloadable link to download purchased files Is there any way to charge customers without an address using stripe ? -
Where to hide password to sql server while deploying django app into Azure from github?
I'm trying to deploy my app on Azure, but I don't know where may I hide a password to SQL server. I usually hide it with decouple module or in environment, but while deploying azure doesn't have access to those. And without this password I get error while running oryx build: raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: PASSWORD not found. Declare it as envvar or define a default value. Does anyone has an idea how to do so? -
Wagtail ValidationError on publish (page revision instance does not exist)
We are facing an issue with Wagtail. Whenever one makes an edit to a page and selects "Publish", they are faced with a ValidationError with the message {'live_revision': ['page revision instance with id 74 does not exist.']} (see screenshot). This only seems to occur when the page is in "Draft" status, though I cannot confirm that this always holds. When I view the page revisions, I can confirm that a revision with ID 74 does indeed not exist. My question is, how might this have occurred, how can we fix it so that we are able to publish the page currently, and what can we do to prevent this from occurring in future? Any assistance is greatly appreciated. I am aware of a similar question on StackOverflow that has already received an answer (Wagtail raises ValidationError on page update), however this answer does not help in our situation as we are not using ParentalKey in any of our models. -
How to get objects with certain foreignkey relationships in ORM?
Assume we have a product model: class Product(models.Model): name = models.Charfield() And a property model where possible properties are defined (like "price", "color", "weight"...): class Property(models.Model): name = models.CharField() And we keep product properties in a separate model: class ProductProperty(models.Model): property = models.ForeignKey(Property) product = models.ForeignKey(Product) value = models.Charfield() I want to get product objects which have certain properties. For instance, I want to get objects only if "price" and "color" is defined for them in ProductPropery table. I obtain the required properties as objects, but I could not solve how can I get products that have all of the given properties. To rephrase, I'm looking for something like this: properties = Property.objects.filter(Q(name__contains="Price") | Q(name__contains="Color")) #this could return one or multiple property objects products = properties.productproperty_set.product_set # imaginary line I made up to show what I want to get I could only think of looping through properties and an inside loop for related ProductProperties to get their products to create multiple lists, and then create a list that's made of common elements (products that are included in each list). -
Display the latest news separately from other
I want to display the latest news on one page separately and all the rest below, but I don't know how this can be done. views.py class PostsView(ListView): model = Post queryset = Post.objects.all().order_by('-date') template_name = 'post/posts.html' urls.py urlpatterns = [ path('', views.PostsView.as_view()), path('<int:pk>', views.PostView.as_view()), path('add/', views.PostFormView.as_view(), name='add'), ] -
how can I add a url for my template in django python?
i use a template im my django homepage.(http://127.0.0.1:8000/) I linked statics files in static folder and formed like {% static .....} when i path it in urls in the main page it work correctly. but when I give it an slug like 'p/' it doesn't work. because it search for statics in p folder: "GET /p/static/post/js/scripts.js HTTP/1.1" 404 2598" my app name is "post" . please help? -
django - edit_entry() missing 1 required positional argument: 'entry'
Helllo, I am getting this error when trying to retrieve the content of util.get_entry(entry). Where shoud I correct this " missing positional argument? Is possible I am getting this error because of my django version? Because it seems to work to a colleague. I tried a code a code that was confirmed to be working to test. Any hint? enter code hereef edit_entry(request, entry): form = EditEntryForm(request.POST) if request.method == "POST": if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] util.save_entry(title,content) return render (request, "encyclopedia/edit.html",{ "content":content, "title":title }) if request.method =="GET": content = util.get_entry(entry) return render(request, "encyclopedia/edit.html", { form: EditEntryForm(entry) }) -
Can you have a function call inside a django form that does a database query before migrations have been fully migrated
I have the following form class RegionForm(forms.Form): REGIONS = get_regions() region = forms.ChoiceField( label='Region', choices=REGIONS) Which I’m importing in my views.py as from forms import RegionForm These views are then imported in the urls.py for use as views from reports.views import ReportView, data_export However, this import is causing the method here REGIONS = get_regions() to be executed. The get_regions function does database query which is causing query exception if the migrations haven’t been applied yet which is usually anytime I’m trying to run the app with a clean database. My question therefore is; Is there a way to prevent the method from being executed immediately after being imported? -
Comparing Datetime and datetimefield django
I am Trying to compare the datetimefield stored in my item to a datetime.date object. Here is the code in views.py where i create instances of datetime.date objects and select the datetimefield of the item from the database and try to compare them. def Comapare(request,pk): Item = item.objects.get(id=pk) date1 = request.GET.get('date1') date2 = request.GET.get('date2') if date1 and date2: if ',' in date1: date1 = list(date1.split(',')) else: date1 = list(date1.split(' ')) if ',' in date2: date2 = list(date2.split(',')) else: date2 = list(date2.split(' ')) date1 = datetime.date(int(date1[0]), int(date1[1]), int(date1[2])) date2 = datetime.date(int(date2[0]), int(date2[1]), int(date2[2])) was_date1_before = date1 < date2 if not date1 < date2: date1, date2 = date2, date1 if date1 < item.date_created: date1 = '' context = { 'date1':date1, 'date2':date2, 'was_date1_before': was_date1_before, 'item': Item, } else: context = {} return render(request, 'Inventory_Management/getDate.html', context) when i am trying to compare them in the above example i get the following error : '<' not supported between instances of 'datetime.date' and 'DeferredAttribute' i tried to search on the internet but didn't really find anything to help. I Get the date from the html file which is the following one {% extends 'Inventory_Management/layout.html' %} {% block body %} <form> <div class="form-group"> <label for="date1">Date 1</label> <input … -
Cannot assign requested address in Django on docker-compose
Someone know how can change the request url in Django? Deacription I'm developing Django app on docker. I'm using 「dj-rest-auth」 for auth system. When I try to registration that API return 500. Error is 「[Errno 99] Cannot assign requested address」. The stack trace wrote like that Request URL: http://containerName/rest-auth/registration/. So Django try to return request url with docker container name. I know that is nomall do Djnago. But I expect change container name to 「localhost」or something. I think it is docker issue... But I don't clear that problem. So if someone know how that solve that , please let me know that. Thanks! Full StackTrace Environment: Request Method: POST Request URL: http://containerName/rest-auth/registration/ Django Version: 3.0.7 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'news.apps.NewsConfig', 'rest.apps.RestConfig', 'users.apps.UsersConfig', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', 'dj_rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.sites', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, … -
Django ValueError: Cannot query "": Must be "User" instance
Hello I am getting a ValueError: Cannot query "": Must be "User" instance. error when creating a user using django-rest-auth. I have created a custom account model in order to do this. serializer.py class RegistrationSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['email', 'username', 'password'] extra_kwargs = { 'password': {'write_only': True}, } def save(self): account = Account( email=self.validated_data['email'], username=self.validated_data['username'], ) password = self.validated_data['password'] account.set_password(password) account.save() return account urls,py app_name = 'account' urlpatterns = [ path('register/', registration_view, name="register"), path('login/', AuthToken.as_view(), name="login"), path('password_reset/', AuthToken.as_view(), name="login"), ] views.py @api_view(['POST', ]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = 'successfully registered new user.' data['pk'] = account.pk data['email'] = account.email data['username'] = account.username token = Token.objects.get(user=account).key data['token'] = token else: data = serializer.errors return Response(data) models.py class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) 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 … -
Crontab format comparision
I want to schedule a cron every Monday at 4:30 in my Django project using django_crontab. I have two formats below. Please suggest if both are same or i should use MON instead of 1 ('30 4 * * MON', 'drc.refresh.test', ['request']) or ('30 4 * * 1', 'drc.refresh.test', ['request']) -
Authorization error while implementing google auhentication in django app
In my django project I have added google authentication API for user login and have deployed that project in heroku server[https://artgreeh.herokuapp.com]. I tried login through Google it worked with no issue in some machine but it's showing error in other machine. error image. In the google I have given redirect url-"https://artgreeh.herokuapp.com/accounts/google/login/callback/". If something is wrong with redirect url then it should not work in any device but it's working in some device.