Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Images not showing on site python/django
I can not see the images/images show up as broken on my site. I checked other questions to this but none have solved my issue. Here is everything I have tried 1) Installed Pillow: imported it in my models.py 2) Settings.py has : MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' 3) Pictures: currently in my "media" folder which sits in my main project directory 4) app/urls.py has: + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and imported settings 5) Template has: {% load static %} and {{ post.image.url }} 6) Collected static 7) Made migrations 8) Ran server settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'profiles/static/') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('post/<id>/', views.post, name='post'), .... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models from django.conf import settings from PIL import Image class Profile(models.Model): title = models.CharField(max_length=200, blank=True, null=True) bio = models.TextField(max_length=500, blank=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) def __str__(self): return f'{self.user.username} Profile' class Post(models.Model): title = models.CharField(max_length=200) post = models.TextField(max_length=100, blank=True) image = models.ImageField(default='default.jpg', upload_to='picsinposts') profile = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title {% … -
using QuerySet to fetch data
I am trying to create a rest api which gives the weather data for a particular city and n days. I've created a model which specifies all the required fields. I've populated the database using management commands. I've tried using Q method to query the database. but I am making error somewhere and I am unable to identify it. #views.py from django.shortcuts import render from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import weatherdata from .serializers import weatherdataserializer from django.http import Http404 from django.db.models import Q # Create your views here. class weatherList(APIView): def get(self, request): weather = weatherdata.objects.all() serializer = weatherdataserializer(weather, many=True) return Response(serializer.data) def post(self, request): serializer = weatherdataserializer(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) class weatherDetail(APIView): def get_queryset(self,*args , **kwargs): queryset_list = weatherdata.objects.all() query = self.request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(city_name__icontains = query) | Q(city_id__icontains = query) ).distinct() return queryset_list #serialisers.py from rest_framework import serializers from .models import weatherdata class weatherdataserializer(serializers.ModelSerializer): class Meta: model = weatherdata # fields = '__all__' fields = ( 'city_name', 'city_id', 'latitude', 'longitude', 'dt_txt', 'temp', 'temp_min', 'temp_max', 'pressure', 'sea_level', 'grnd_level', 'humidity', 'main', 'description', 'clouds', 'wind_speed', 'wind_degree', ) #models.py from … -
How to send zip file as an attachments to an email Django
I wanted to send a zip file as an attachment. email_object = EmailMessage(subject='subject', from_email="email", to=["to_email"]) email_object.attach_file('zipped_folder') email_object.send() -
Automatically setting image depending on the post category in Django
I need a code that will automatically set the photo assigned to the post depending on its category. Initially, I thought about changing the default attribute but I have no idea how to implement it. here is my model: class Post(models.Model): CATEGORY_CHOICES = ( ('Django', 'Django'), ('Python', 'Python'), ('C++', 'C++'), ('Graphics', 'Graphics'), ('Text Editor', 'TextEditor'), ('Spreadsheet', 'Spreadsheet'), ('DataBase', 'DataBase'), ('Web Design', 'WebDesign'), ) title = models.CharField(max_length=50, unique=True) content = MDTextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default_post_pic.jpg, upload_to='post_pics') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 200 or img.width > 200: output_size = (200, 200) img.thumbnail(output_size) img.save(self.image.path) -
AttributeError: module 'posts.views' has no attribute 'edit'
I am trying to import the views created from my views.py file to my urls.py file for my django project. After doing so, the terminal displays an attribute error. I am following a tutorial that says it works and I do not know what to do I've tried everything. I've also checked stack overflow messages. Nothing has helped. posts/views.py from django.shortcuts import render, redirect, get_object_or_404 from .forms import PostForm from .models import Post from django.views.generic import ListView, DetailView # Create your views here. class IndexView(ListView): template_name = 'posts/index.html' context_object_name = 'post_list' def get_queryset(self): return Post.objects.all() class PostDetailView(DetailView): model = Post template_name = 'posts/post-detail.html' def postview(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save() return redirect('index') form = PostForm() return render(request, 'posts/post.html', {'form': form}) def edit(request, pk, template_name='posts/edit.html'): post = get_object_or_404(Post, pk=pk) form = PostForm(request.POST or None, instance=post) if form.is_valid(): form.save() return redirect('index') return render(request, template_name, {'form': form}) def delete(request, pk, template_name='posts/confirm_delete,html'): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': post.delete() return redirect('index') return render(request, template_name, {'object': post}) posts/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.PostDetailView.as_view(), name='detail'), path('edit/<int:pk>/', views.edit, name='edit'), path('post/', views.postview, name='post'), path('delete/<int:pk>/', views.delete, name='delete'), ] The website is … -
How to send an unknown number of filter values to DRF with React? GET or POST?
I am building a filtering system where you can filter products by brand and category. The user selects the filters in a React Application and this triggers a request to the backend API (Django Rest Framework - DRF) that is either GET or Post. Ideally Django would receive the filter names as value it can iterate over. I am quite lost on how to achieve this. A GET request would be possible. But in order for DRF to work with the request it needs to have a uri-format as such: http://127.0.0.1:8000/filter/?categories=proviant&categories=multipower&brands=kellogs I could then use a view like this to grab the values. class ProductFilterListView(APIView): def get(self, request): for el in request.GET.getlist('categories'): print(el) return Response('') This is quite a challenge since axios (library for making JS requests) does not have an option to format the url according to the requirements of DRF. So this feels very wrong and very manual and is hardly a "good" solution (?) The other way would be to use a post request. But then again, I have never used a post request for something that does not have a serializer or a form on the Django side. So, I would not know how to validate … -
Design correct relations of modes in Django
Please help to correct design the next things. Need to have to teams list of stings which are connected to the list of companies. After this I want to use them to user model. I did it in next way : class CustomCompany(models.Model): company_name = models.CharField(max_length=30, default="None", unique=True ) class CustomTeam(models.Model): team_name = models.CharField(max_length=30) company_name = models.ForeignKey(CustomCompany, on_delete=models.CASCADE, related_name='company_name+', to_field='id', ) class CustomUser(AbstractUser): def _get_self_company(self): return self.company phone = models.CharField(max_length=20, blank=True) company = models.ForeignKey(CustomCompany, on_delete=models.CASCADE, default='None', to_field='company_name', related_name='company' ) team = models.ForeignKey(CustomTeam, on_delete=models.CASCADE, to_field='team_name', related_name='team_name+', limit_choices_to={"company_name__id":_get_self_company}, ) Not sure if it's correct, but the main issue in it, that I should specify unique team model, but it shouldn't be. users.CustomUser.team: (fields.E311) 'CustomTeam.team_name' must set unique=True because it is referenced by a foreign key. Help please to understand how to correct do this? -
Mobile Apps with Django BackEnd
Hello? I have an SMS based Django app. I want to create a Mobile app that syncs records to and fro from my Django app database. How can I go about this? Thanks in advance. -
Unknown element errors in VueJS+Django
I added Vue to my Django project using Webpacks. I'm now testing my Vue frontend with some default templates provided by Vue itself. Here is what i tried: App.vue <template> <v-app id="inspire"> <v-navigation-drawer fixed v-model="drawer" app > <v-list dense> <v-list-tile @click=""> <v-list-tile-action> <v-icon>home</v-icon> </v-list-tile-action> <v-list-tile-content> <v-list-tile-title>Home</v-list-tile-title> </v-list-tile-content> </v-list-tile> <v-list-tile @click=""> <v-list-tile-action> <v-icon>contact_mail</v-icon> </v-list-tile-action> <v-list-tile-content> <v-list-tile-title>Contact</v-list-tile-title> </v-list-tile-content> </v-list-tile> </v-list> </v-navigation-drawer> <v-toolbar color="indigo" dark fixed app> <v-toolbar-side-icon @click.stop="drawer = !drawer"></v-toolbar-side-icon> <v-toolbar-title>Application</v-toolbar-title> </v-toolbar> <v-content> <v-container fluid fill-height> <v-layout justify-center align-center > <v-tooltip right> <v-btn icon large :href="source" target="_blank" slot="activator"> <v-icon large>code</v-icon> </v-btn> <span>Source</span> </v-tooltip> </v-layout> </v-container> </v-content> <v-footer color="indigo" app> <span class="white--text">&copy; 2017</span> </v-footer> </v-app> </template> main.js import Vue from 'vue' import App from './App' import Vuetify from 'vuetify' Vue.use(Vuetify) Vue.config.productionTip = false export default new Vuetify({ }) /* eslint-disable no-new */ new Vue({ el: '#app', vuetify: new Vuetify(), drawer: false, template: '<App/>', components: { App } }) The problem is that, when opening my localhost, nothing is rendered and i get a lot of errors on my dev tools, such as: [Vue warn]: Property or method "drawer" is not defined on the instance but referenced during render. [Vue warn]: Property or method "source" is not defined on the instance but referenced during … -
Django: Filter for all actions related to the ForeignKey Object
I've got a Model called User which looks like this: class User(AbstractBaseUser, PermissionsMixin): ...some fields... club = models.ForeignKey('schedule.Club', on_delete=models.CASCADE, null=True, blank=True) And for my APP I'm creating History Items, which I want to let my users see if they're logged in. So far I only show History Items that are related to them: class HistoryItems(ListView): model = HistoryItem template_name = 'history/history_items_table.html' context_object_name = 'history_items' def get_context_data(self, **kwargs): history_item_query = HistoryItem.objects.filter(Q(changed_by=self.request.user) | Q(object_id=self.request.user.pk)).select_related('changed_by', 'content_type') return { 'filter_history_form': HistoryFilterForm(), 'history_items': history_items, } So if they get changed or change something themselves they can see that. But now I also want to show them all changes that were done to the Club that they have chosen. So for example if "User1" has "Club1" as ForeignKey, and I change the name of Club1 to Club2 I want the User1 to see that in the history items. My History Model looks like this: class HistoryItem(models.Model): changed_at = models.DateTimeField('Changed At', auto_now_add=True) description = models.TextField('Description', max_length=300) changed_by = models.ForeignKey('users.User', on_delete=models.SET_NULL, related_name="history_items", null=True) action = models.CharField('Action', max_length=50, choices=ACTION_CHOICES) difference = JSONField('Differences', encoder=DjangoJSONEncoder, null=True, blank=True) # Generic object foreign key object_id = models.IntegerField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) content_object = GenericForeignKey('content_type', 'object_id') How would I have to "rebuild" my history_item_query … -
Django - How to list items by their common tags
I'm a django/python beginner working on a basic blog and attempting to list items by their tags. I'm able to add tags to posts from the admin panel, but haven't been able to figure out the proper code that will allow me to display posts by their particular tags. I have tried to implement many solutions found online, but I've just ended up listing every post, no posts, or gotten errors. Here is the relevant part of my models.py: ... class Tag(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') tags = models.ManyToManyField(Tag) updated_on = models.DateTimeField(auto_now=True) content = RichTextUploadingField(config_name="default", null=True, blank=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title views: ... class TagPage(generic.ListView): model = Tag template_name = 'tag_list.html' and urls: urlpatterns = [ ... path('tag/<slug>/', views.TagPage.as_view(), name='tag') ] If anyone has any ideas as to what code is necessary, it would be appreciated. -
Django - auth models in default database, other models replicated in several databases?
I am wondering whether it's possible in Django to run a multi-database project with following definition: All core models (User, Group, Session, Customer, etc.) in the database 'default'. All other models (Order, Invoice, etc.) in multiple databases, where each database belongs to single Customer. ------------ | default | ------------ | User | | Group | | Customer | ------------ / | \ ------------ ------------ ------------ | cust_A | | cust_B | | cust_C | ------------ ------------ ------------ | Order | | Order | | Order | | Invoice | | Invoice | | Invoice | ------------ ------------ ------------ I know I can specify a database for particular model, but that would not work in this case. I need models Order and Invoice to be created in databases cust_A, cust_B, cust_C, while models User, Group and Customer need to be created only in default database. Working with such setup should be possible by manually selecting a database for a QuerySet with .using('db_name'). Is it possible to create such DB structure for Django project? -
Python Django - crispy forms layout
I am trying to edit layout of my form via forms.py. But if I try to set it up nothing happens and the form layout keeps the default layout. Here is my models.py: class AssetReceived(models.Model): asset_user = models.ForeignKey(no_models.MyUser,on_delete=models.CASCADE, related_name='my_user_profile2') asset_received = models.ForeignKey(Asset, on_delete=models.CASCADE) asset_servicetag = models.CharField(blank=True, max_length=7) asset_date = models.DateField(default=datetime.date.today) asset_status = models.ForeignKey(AssetStatus, on_delete=models.CASCADE) asset_note = models.CharField(blank=True, max_length=250) asset_order_type = models.ForeignKey(AssetOrderType, on_delete=models.CASCADE) asset_order_refresh = models.ForeignKey(AssetStoreMaster, on_delete=models.CASCADE, blank=True, null=True, related_name='sc_refresh') asset_order_install = models.ForeignKey(AssetStoreMaster, on_delete=models.CASCADE, blank=True, null=True, related_name='sc_install') asset_order_deinstall = models.ForeignKey(AssetStoreMaster, on_delete=models.CASCADE, blank=True, null=True, related_name='sc_deinstall') here is my views.py: class ReceivedAssetCreate(generic.CreateView): template_name = 'received_asset/received-asset-new.html' form_class = ReceivedAssetForm def get_success_url(self): return reverse('received_asset:received-asset-new') def post(self, request): form = self.form_class(request.POST) if form.is_valid(): form.save(commit=True) messages.success(request, f'Received asset has been received successfully') return render(request, self.template_name, {"form": form}) here is my forms.py: class ReceivedAssetForm(forms.ModelForm): asset_user = forms.ModelChoiceField(queryset=no_models.MyUser.objects.all(), widget=autocomplete.ModelSelect2()) asset_servicetag = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Service Tag'})) asset_date = forms.DateInput asset_note = forms.CharField(required=False) asset_order_type = forms.ModelChoiceField(queryset=AssetOrderType.objects.all()) asset_order_refresh = forms.ModelChoiceField(queryset=AssetStoreMaster.objects.all(), required=False) asset_order_install = forms.ModelChoiceField(queryset=AssetStoreMaster.objects.all(), required=False) asset_order_deinstall = forms.ModelChoiceField(queryset=AssetStoreMaster.objects.all(), required=False) asset_received = forms.ModelChoiceField(queryset=Asset.objects.all(), widget=autocomplete.ModelSelect2()) asset_status = forms.ModelChoiceField(queryset=AssetStatus.objects.all(),widget=autocomplete.ModelSelect2()) class Meta: model = AssetReceived fields = ['asset_user', 'asset_received', 'asset_servicetag', 'asset_date', 'asset_status', 'asset_note', 'asset_order_type', 'asset_order_refresh', 'asset_order_install', 'asset_order_deinstall'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( 'asset_user', Row( Column('asset_received', css_class='form-group col-md-6 mb-0'), Column('asset_servicetag', … -
How to implement multiple user types with different roles and permissions in Django?
I'm new to web development using Django Framework and Python programming language and I am tasked to make a mini project that implements the following: Permissions Management; Roles Management; Users Accounts Management; Login and Logout; and Password Reset. What are the appropriate steps for me to accomplish this? I have read about user authentication and permissions and custom user models but the examples that were given were less complicated than what I actually needed. I have to set up an application that implements multiple user accounts wherein each user can have multiple roles and each roles have different permissions. I know that Django has built-in functions to do this but I want to make my own customization as mush as possible. I would like to know if creating Custom User Model extending AbstractBaseUser is the best option there is to accomplish this. Also, I would like to know how to customize the Django built-in admin page, such as replacing or deleting unnecessary fields. -
can't distribute django project by elasticbeanstalk
I wanna distribute django-project to use ElasticBeanStalk. But there's problem when I do 'eb create' code. Honestly, I saw hundreds of documents for this problem. Someone says it is 'pillow' package problem, pip problem, etc. But I think pythonpath problem. Here's my errorcode and ElasticBeanStalk application log. 2019-08-14 04:56:44 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2019-08-14 04:56:48 ERROR [Instance: i-0e32d61b630bb7337] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. Here's EB logs /var/log/eb-activity.log Collecting future==0.16.0 (from -r /opt/python/ondeck/app/requirements.txt (line 13)) Downloading https://files.pythonhosted.org/packages/00/2b/8d082ddfed935f3608cc61140df6dcbf0edea1bc3ab52fb6c29ae3e81e85/future-0.16.0.tar.gz (824kB) Collecting idna==2.7 (from -r /opt/python/ondeck/app/requirements.txt (line 14)) Could not find a version that satisfies the requirement pywin32==224 (from -r /opt/python/ondeck/app/requirements.txt (line 22)) (from versions: ) No matching distribution found for pywin32==224 (from -r /opt/python/ondeck/app/requirements.txt (line 22)) You are using pip version 9.0.1, however version 19.2.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. 2019-08-14 04:56:44,147 ERROR Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 Traceback (most recent call last): File … -
How to display serializers validation error message in vue template?
Here i am using vue.js for the client side rendering and django-rest framework for the server side.I am customizing the PasswordResetSerializer class in order to check whether the entered email is registered in our database or not.If the email is not in our db then it does not send the success message which is good but also it does not display the validation error messgae but i have configured the error message in the PasswordResetSerializer class if there is not user with that email address. Note:It is displaying the success message Password reset email has been sent if the email address is in our database. How can i display the serializers.ValidationError message in my login form ? serializers.py from django.contrib.auth.forms import PasswordResetForm from django.conf import settings class PasswordResetSerializer(serializers.Serializer): email = serializers.EmailField() password_reset_form_class = PasswordResetForm def validate_email(self, value): self.reset_form = self.password_reset_form_class(data=self.initial_data) if not self.reset_form.is_valid(): raise serializers.ValidationError('Error') if not User.objects.filter(email=value).exists(): raise serializers.ValidationError('Sorry.No user found with that email address.') return value def save(self): request = self.context.get('request') opts = { 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'request': request, } self.reset_form.save(**opts) loginform.vue <template> <div class="login-card"> <div class="container"> <form @submit.prevent="login(credentials.username, credentials.password)"> <div class="input-container"> <img class="icon-user" src="@/assets/icons/user.png" alt=""> <input class="username" type="text" placeholder="Username" v-model="credentials.username" name="username" required> </div> <div class="input-container"> <img class="icon-password" … -
Django admin Inline is not displayed, without any error
I have a Shelter model which is the parent of Suite model and for Suite model I created an admin inline to define some constrains on it. class Shelter(models.Model): title = models.CharField(max_length=255, verbose_name=_('Title')) city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name=_('City')) address = models.CharField(max_length=255, verbose_name=_('Address')) class Suite(Shelter): room = models.IntegerField(verbose_name=_('Room')) class SuiteConstrain(models.Model): suite = models.ForeignKey(Suite, on_delete=models.CASCADE, verbose_name=_('Suite')) start_date = jmodels.jDateField(verbose_name=_('Start Date')) end_date = jmodels.jDateField(verbose_name=_('End Date')) req_limit = models.IntegerField(verbose_name=_('Request Count Limit')) req_max_attendants = models.IntegerField(verbose_name=_('Max Attendants')) req_max_nights = models.IntegerField(verbose_name=_('Max Nights')) And in my admin.py: class ShelterAdmin(ModelAdminJalaliMixin, admin.ModelAdmin): form = ShelterForm inlines = [ShelterPictureInline, ] list_display = ('title', ) class SuiteConstrainInline(admin.TabularInline): model = SuiteConstrain extra = 1 @admin.register(Suite) class SuiteAdmin(ShelterAdmin): inlines = [SuiteConstrainInline, ShelterPictureInline] pass with a great surprise I have now just ShelterPictureInline visible in my admin panel. ConstrainInline Doesn't show without any error! -
how do i count and make a table from the data
i have two tables that is the occurrance table and waterbody table,i want to view how many species occur in a particular waterbody i have already listed down the water bodies but now picking and counting the number of species in each water body is the problem this is my def occurrance water_body = WaterBody.objects.get(name=water_body), this is my models.py water_body = models.ForeignKey(WaterBody, blank=True, null=True, on_delete=models.SET_NULL) this is my water_analytics.html <tbody> <tr> <td>Lake Victoria</td> <td>{{w.id.name.count }}</td> </tr> <tr> <td>Kazinga Channel</td> <td>{{occurance.count}}</td> </tr> i expect to output the number of number of species in a particular waterbody please help me as quickly as you can -
API Django post url return 403 forbidden error
I am using rest-framework-api for my project and I am trying to create a User using an endpoint with a POST method. However, the response is always 403 Forbidden -> (CSRF token missing or incorrect.): I have tried all the methods on stackoverflow : csrf_exempt decorators, authentication_classes = [], CsrfExemptMixin And none of these methods works ... I always get the same answer "403 Forbiddden" PS : I am sending request with POSTMAN API : permission_classes = (AllowAny,) authentication_classes = [] # Serializer class to validate input and serialize output # Can be overridden by get_serializer_class() queryset = User.objects.all() serializer_class = UserSerializer` Url: api.register(r'auth/sign-up', views.UserEP, basename='userEP') My aim is just to implement an endPoint that allows any user to create an account. -
Django factory-boy - maximum recursion depth
I have a User, Profile and Shop model. The former two are from the common recipes page on the official documentation: @factory.django.mute_signals(post_save) class UserFactory(factory.DjangoModelFactory): class Meta: model = User profile = factory.RelatedFactory(ProfileFactory, 'user') @factory.django.mute_signals(post_save) class ProfileFactory(factory.DjangoModelFactory): class Meta: model = models.Profile # We pass in profile=None to prevent UserFactory from creating another profile # (this disables the RelatedFactory) user = factory.SubFactory('accounts.factories.UserFactory', profile=None) shop = factory.RelatedFactory('shops.factories.ShopFactory') class ShopFactory(factory.DjangoModelFactory): class Meta: model = models.Shop owner = factory.SubFactory(UserFactory) url = factory.Faker('url') The error comes from declaring a shop on the profile. How should I change the code for it to work properly with the ShopFactory? Thanks! -
Postgres DateTimeField incorrect time
I have in my module DateTimeField: class Pairs(models.Model): id = models.AutoField(primary_key=True) timestamp = models.DateTimeField(null=True) and I insert data from python like this: timestamp = datetime.fromtimestamp(pair['timestamp']) tz_aware_datetetime = timestamp.replace(tzinfo=pytz.timezone('Asia/Jerusalem')) pair_recored =Pairs(session=session_obj,timestamp=tz_aware_datetetime) pair_recored.save() the timestamp from my code is: 2019-08-15 08:50:07.795000+02:21 but in my DB this field has different value: 2019-08-15 09:29:07.795+03 why there is this difference between these values? -
How to get sublime text 3 editor to auto-complete the "{% " with " %}" to save time?
I have started developing django apps with Sublime Text 3, and find the "{% %}" brackets in jinja logic to be very tedious to type, so i wonder is there a way to auto-complete the "{% " bracket with " %}" to save some time? -
Why Django application can't connect to remote MySQL database in Docker container?
I have Django application which works with remote MySQL database. I run application with the help of docker container. Unfortunatly in logs of the application I notice error. When I am using my application without Docker it works. Why can't an application running in Docker connect to the database? ERROR Internal Server Error: /main/login/ Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/beewifi/main/views/auth.py", line 47, in wifi_login zone = Zone.objects.get(identity=params['identity']) File "/usr/local/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 374, in get num = len(clone) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 232, in __len__ self._fetch_all() File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 1105, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 863, in execute_sql sql, params = self.as_sql() File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 420, in as_sql where, w_params = self.compile(self.where) if self.where is not None else ("", []) File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 373, in compile sql, params = node.as_sql(self, self.connection) File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/where.py", line 79, in as_sql sql, params = compiler.compile(child) … -
path function for URL throwing error when we want to capture an integer or slug paramter
I am a beginner in django 2.2.4. I was trying to the following the urls.py file. from firstapp import views from django.contrib import admin from django.urls import re_path, path urlpatterns = [ re_path(r'^admin/$', admin.site.urls), re_path(r'^$', views.index), path('articles/2003/', views.index), path('articles/<int:year>/', views.index), ] I see that the url http://127.0.0.1:8000/articles/2003/ executes the views.index. However, when I run the url http://127.0.0.1:8000/articles/2005/ ,there is an error. Request URL: http://127.0.0.1:8000/articles/2005/ Django Version: 2.2.4 Exception Type: TypeError Exception Value: index() got an unexpected keyword argument 'year'enter code here Why is this not working? As above.It was expected this ur would be matched by the linee path('articles//', views.index). -
How to insert items into Django models from views.py file?
I'm trying to insert an item into my database record from the views.py file. How can I do this?