Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djongo ArrayReferenceField in Django Admin Panel Error
Whenever I try to go to the product details page I encounter this error - 'list' object has no attribute '_meta' How to solve it? My models class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=255, blank=False, null=False) price = models.IntegerField(blank=True, null=True, default=0) category = models.ArrayReferenceField( to=Category, blank=True, related_name="products" ) def get_categories(self): return "\n".join([p.name for p in self.category.all()]) admin @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ('name','price', 'in_stock','get_categories',) I'm using Django - 3.1.7 , djongo - 1.3.4 -
A WP form sending data through API to Web App in Azure?
Our team has been working this Django based Web App for handling customer data. This customer data is being gathered in a json Rest Api and the form the API connects to is made with WordPress. The database is parked in Azure and is working very well, but now our concern is that we need some kind of Azure token to get the data from the form and API to the database in Azure. Azure also has some restrictions what it lets through as only the customer's organization can access the Web app/database in azure as it is behind MS login. So my question is: is there something we are missing? We know we need a token for the post as that way it cannot be anything other than a "legit" form that was filled out on the public web page. But the way we are trying to get that token hasn't worked. The Form gets the info that needs to be filled form the API and it is done by the marketing agency that creates the Customer's web page. So is this something they need to add to the form or Us for the API side? Also sorry for … -
can't check username and email and password using UserCreationForm - Django
when i add style to UserCreationForm in forms.py and pass it to signup html page and test it , it don't work fine i mean it don't check username and email if it exist or not and password don't check if it good or no singup.html : <form method="post"> {% csrf_token %} {% for field in form %} <fieldset class="control-group"> <label class="control-label" for="id_{{ field.name }}">{{ field.label }}</label> <div class="controls"> {{ field }} <p class="help-text">{{ field.help_text }} </p> </div> </fieldset> {% endfor %} <input type="submit" class="fadeIn fourth" style="background-color:#7952b3" value=" sign up "> </form> forms.py : from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm # Sign Up Form class SignUpForm(UserCreationForm): first_name = forms.CharField(required=True,label=' First Name : ',widget=forms.TextInput(attrs={'class': 'form-control'}) ) last_name = forms.CharField(required=True,label=' Last Name : ',widget=forms.TextInput(attrs={'class': 'form-control'}) ) email = forms.EmailField(required=True,label=' Email ',widget=forms.EmailInput(attrs={'class': 'form-control center container','style': 'width:85%;text-align: center;background-color:#f6f6f6'}) ) # constructor of the UserForm, not Meta def __init__(self, *args, **kwargs): super().__init__(*args,**kwargs) self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':' add username ','style': 'font-size:19px;text-align: center;'}) self.fields['password1'].widget.attrs.update({'class':'form-control','placeholder':' enter pass ','style': 'font-size:19px;text-align: center;'}) self.fields['password2'].widget.attrs.update({'class':'form-control','placeholder':' re-type pass ','style': 'font-size:19px;text-align: center;'}) class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', ] how i can fix check username and email and password -
Database performance in Django/Postgres
In one of my views for the staff, I show the last 10 registrars on my site and some of their activity like so: recentlyjoined = User.objects.order_by('-date_joined').annotate(post_count=Count('post', distinct=True), text_count=Count('text', distinct=True), pdf_count=Count('pdf', distinct=True), discussion_count=Count('discussion', distinct=True))[0:10] And in my template I do {% for applicant in recentlyjoined %} {{ applicant.post_count }} {% endfor %} for all the annotations above. When I call this site, it takes VERY long to load, sometimes I even get a timeout error. I narrowed it down to this annotations. Whats wrong? Why does this improve so bad? And how can I fix it? (And in case it matters: In my sandbox database I have only 15 users, but one of them has like 5000 posts. So its not exactly big data to handle.) -
How to make multiple types of models and refer them with same name in Django?
I am new to Django. I want the functionality of Accounts and Transactions. Account can have three types of transactions. Income, Expense and Transfer. All of them have some common fields among them. But also have some additional fields. I want to know can I make such models so that I can access all the transactions of account. And I also want to use them in rest framework. Is it possible to do so? -
Can I build a serializer that validates username and email existence on is_valid call?
guys! I have this serializer class for the user model class UserSerializer(serializers.ModelSerializer): username = serializers.RegexField("^(?=.{6,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$") full_name = serializers.RegexField("^([a-zA-Z]{2,}\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\s?([a-zA-Z]{1,})?)") email = serializers.EmailField() phone = serializers.RegexField("^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$") class Meta: model = User fields = ['username', 'full_name', 'email', 'password', 'phone'] This is my serializer class for the moment. I want to validate that the username and email does not exist before saving an user. Can I do it without manually writing the validations? And I also need to validate the regex for the username and the email field for the email Thank you! -
Create custom filter in popup of inlines. DjangoAdmin
Is it possible to create filter for one field in object creating in django admin. For example, i need to add Video when creating Collection object, so i create class VideoInline(admin.TabularInline): fields = ('video', ) model = Collection.videos.through But i need to filter videos in this popup by some fields, like created_at and so on. Is it possible to do it? Models: class Collection(CreatedByModel, UpdatedByModel): name = models.CharField( max_length=150, verbose_name='Название подборки', unique=True, ) videos = models.ManyToManyField( Video, through=CollectionVideoLink, verbose_name='Видео подборки', related_name='collection', ) class Video( # noqa: WPS215 SoftDeleteModelMixin, ReversionModelMixin, DirtyFieldsMixin, CreatedByModel, ): uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True, ) class CollectionVideoLink( CreatedByModel, UpdatedByModel, ): video = models.ForeignKey( Video, on_delete=models.deletion.CASCADE, verbose_name='Video', ) collection = models.ForeignKey( 'Collection', on_delete=models.deletion.CASCADE, verbose_name='Collection', ) -
My django project isn't logging out, giving weird error
I'm getting a weird error when I try to log out a user on my django project: This is my logout view: from django.contrib.auth import logout def logout_now(request): logout(request) What is the problem? -
Azure webapp module not found
my webapp is giving me error module not found "dateutil" every 10minutes. When I go into SSH and install it manually with pip install python-dateutil it works for that 10minutes. But after a while it just writes same error. When I put it into requirements.txt it won´t let me put application up. Any reason why is azure app doing this or what to check? Thanks in advance. -
Socket Programming between Django REST API, VUE and Scrapy
Write now my code is able to successfully send a post request to the Django REST API which in result triggers the spider respectively and stores its output to the database successfully. For this cause I am using scrapyd API as you can see in the below code snippet @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def crawlRottenTomatoes(request): print("in crawl tottentomatoes method") url = request.data["url"] if not url: return JsonResponse({'error': 'Missing args'}) if not is_valid_url(url): return JsonResponse({'error': 'URL is invalid'}) domain = urlparse(url).netloc msg_dic = {} try: scrapyd.schedule(project="movie_spider", spider="rottentomatoes", url=url, domain=domain) msg_dic['msg'] = "Spider RottenTomatoes for given url is up and running" except Exception as e: print("exception") msg_dic['error'] = "Error running spider for RottenTomatoes" return JsonResponse(msg_dic, safe=False) But now what I want. Is to have some kind of response back from the scrapyd when it's done crawling and parsing the website/channel for that I came across the WebSockets. I tried to use WebSockets but the problem is scrapyd is a demon itself. I am not really able to send a message to the WebSocket client from the scrappy. Does anyone have any idea of how do to do or can share some resources which can help me with this? -
django Inserting textbox for a debateapp
So I am building this debate app where a question is posted and the user chooses the option to agree,disagree or have a neutral opinion. When the user chooses the option I want them to type the reason in textbox after choosing the option and then submit. After submitting they get to see other users choice. I have build until choosing the options in the vote page and displaying the result but I could not get the textbox. here is my code: models.py from django.db import models from django.conf import settings from django.contrib.auth.models import User class Poll(models.Model): question = models.TextField() option_one = models.CharField(max_length=30) option_two = models.CharField(max_length=30) option_three = models.CharField(max_length=30) option_one_count = models.IntegerField(default=0) option_two_count = models.IntegerField(default=0) option_three_count = models.IntegerField(default=0) #point = models.TextField() def total(self): return self.option_one_count + self.option_two_count + self.option_three_count class textbox_model(models.Model): Poll = models.ForeignKey(Poll,on_delete=models.CASCADE) body = models.TextField(max_length = 5000 , null=False,blank=False) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.body forms.py from django.forms import ModelForm from .models import Poll,textbox_model from django import forms class CreatePollForm(ModelForm): class Meta: model = Poll fields = ['question', 'option_one', 'option_two', 'option_three'] class EditTextbox(forms.ModelForm): class Meta: model = textbox_model fields = ('body',) widgets = { 'body': forms.Textarea(attrs={'class':'form-control'}), } views.py def vote(request, poll_id): poll = Poll.objects.get(pk=poll_id) if request.method == … -
Missing dependencies error trying to install Postgis on Python docker container
I'm trying to add the next libraries to add support for geospatial data to my Django project: binutils libproj-dev gdal-bin postgresql-postgis So I updated my Dockefile with the next line: FROM python:alpine RUN apk update && apk add --no-cache \ binutils \ libproj-dev \ gdal-bin \ postgresql-postgis I know the missing dependencies error is due to I'm using the Linux alpine python image, but I don´t know how to add the corresponding repositories or what are those. -
Django Imagefield not saved
Although I select images in the form, image changes do not saved. Other inputs are saving. Help me pls. HTML: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{settingform}} <button type="submit">Save</button> </form> models.py: from django.db import models class SiteSetting(models.Model): logo = models.ImageField(blank=True, verbose_name="Logo") @property def logo_url(self): if self.logo and hasattr(self.logo, 'url'): return self.logo.url views.py: def SiteSettingsView(request): settings = SiteSetting.objects.all() settingform = SiteSettingForm(instance=settings[0]) if request.method == 'POST': settingform = SiteSettingForm(request.POST, instance=settings[0]) if settingform.is_valid(): settingform.save() return redirect('home') context = { 'settings': settings[0], 'settingform': settingform } return render(request, 'x.html', context) forms.py: from site_setting.models import SiteSetting class SiteSettingForm(forms.ModelForm): class Meta: model = SiteSetting fields = '__all__' -
Import Django settings from app into project settings?
I've got a few projects that all use a 'shared_app'. In that shared_app I have a module named default_settings.py that contains the settings that are used by all projects that have that shared_app. Folder structure is the usual Django structure: project_dir | - project_dir | - settings.py - urls.py - wsgi.py - shared_app | - default_settings.py - ... all other app files ... - other_app - some_other_app - ...other project files.... In my project_dir/settings.py I have these lines: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) exec( open(os.path.join(BASE_DIR, "shared_app", "default_settings.py")).read() ) in globals() # Below this line - I can use any settings from default_settings.py if DEBUG: SESSION_EXPIRE_AT_BROWSER_CLOSE = False The default_settings.py files contains things like: DEBUG = is_debug(os.environ.get("DJANGO_DEBUG")) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY") SESSION_EXPIRE_AT_BROWSER_CLOSE = True There are simply too many settings in default_settings.py to have something like from share_app import THIS, THAT, OTHER There are around 20-30 settings. Is there a better way to do this? Or am I stuck with that slightly confusing, ugly exec() command? Is there anything more 'pythonic'? -
Question about loops in python and django
Is it possible to loop two variables within the same for loop. {% for item in list_qr_images %} <tr style='mso-yfti-irow:0;mso-yfti-firstrow:yes;page-break-inside:avoid; height:47.5pt'> <img src="static/images/0'qr.jpg" align="center" style=" padding-left: 3px; padding-right: 30px; padding-bottom: 20px; padding-top: 20px;"> </tr> {% endfor %} When i cast the first loop selecting my qr images i also need to select a diferent variable with a serial number for the item is it possible to do it with an 'and' statement like for example: {% for item in list_qr_images and serial %} Or is there another way to do it. -
Django buttons loading more posts on click
I want to implement the loading of the following posts in the news on a button click using ajax. So far it turned out to load the same number of posts when pressed. Those. I immediately see 5, then I pressed another 5. And so on. I want to make sure that after the first 5 posts, they are loaded further not by 5, but by 8. But it just doesn't work. views.py class NewsView(ListView): template_name="mebelain/news.html" queryset = News.objects.all().order_by("-date_news") class NewsJsonListView(View): def get(self, *args, **kwargs): upper = kwargs.get('num_news') lower = upper - 5 all_news = list(News.objects.values()[lower:upper]) return JsonResponse({'all_news':all_news}) urs.py urlpatterns = [ path('news', views.NewsView.as_view(),name='news'), path('json_news/int:num_news/', views.NewsJsonListView.as_view(),name = "json_news") ] script.js let visible = 5 const hadleGetData = () => { $.ajax({ url: `/json_news/${visible}/`, type: 'get', success: function(response) { const data = response.all_news data.map(news => { console.log(news.id) }) }, error: function(error) { console.log(error) } }) } hadleGetData() window.addEventListener("load", News) function News() { const loadBtn = document.getElementById('load-btn') loadBtn.addEventListener('click', () => { visible += 5 hadleGetData() }) } What do I need to fix so that I can load posts as described above? -
How to change for loop variables in python/django while for loop is running
I want to change variables that define a for loop while the loop is running. It will make more sense when you see the code, so here it is: days = form.instance.days for i in range(0, days + 1): days_added = i current_end = class_start_date + datetime.timedelta(days=days_added) current_end_day = calendar.day_name[datetime.datetime.strptime(str(current_end), '%Y-%m-%d').weekday()] if current_end_day == 'Saturday' or current_end_day == 'Sunday': days = days + 1 You see, when I run the code days = days + 1, I want the days for for i in range(0, days + 1): to be updated, so that the number of total loops of the forloop will be increased by 1 whenever days = days + 1 occurs. days = form.instance.days is increased by 1, but days in for i in range(0, days + 1): is not updated. I hope you guys could help. Thanks. -
Django ImportError: Module does not define attribute/class
I am trying to add a custom/overridden AdminSite because I need a different template for the Admin. I did everything as the Docs said: https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#customizing-the-adminsite-class class NewAdminSite(AdminSite): index_template = 'admin/index.html' site_header = 'Administration' admin_site = NewAdminSite(name='newadmin') ofc I added admin_site.urls instead of admin.site.urls to urls.py, created a custom AdminConfig in apps.py, and added that new AdminConfig to installed Apps instead of django.contrib.admin. The Problem is that I now receive this: AdminSiteClass = import_string(apps.get_app_config('admin').default_site) File "C:\Users\User.virtualenvs\ssccms-fGQRLLK4\lib\site-packages\django\utils\module_loading.py", line 24, in import_string ) from err ImportError: Module "project.admin" does not define a "NewAdminSite" attribute/class -
Change error_messages for a specific error in specific a field and for another error for all fields (Django)
Say I have 30 fields in my model where one of them is link. I want to throw a specific error when link is invalid, and I want to change the required error for all the fields (including link). If I write the following form: class product_prices_form(forms.ModelForm): class Meta: error_messages = {"link":{"invalid": "Not really valid"}, #Only change invalid for link-field "required":"You forgot something here!"} #Change the "required" error for all fields model = my_model the required error is not overwritten. If I move it into the "link" dict, it works fine, but creating that for all the remaining 29 fields i doubt is the right way to do. -
¿Cómo puedo evitar que un producto ya existente en una remisión/venta vuelva a alterar el stock al editar la venta?
Buen día mundo, lo que intento hacer es editar mi remisión/venta, en caso de que quiera agregar algún otro articulo, el problema es que al guardar los cambios vuelve a alterar el stock de los productos que ya estaban registrados. Todo esto lo estoy trabajando con Python y Django, mi base de datos es en SQLite3. Les dejo mis bloques de código, en caso de que se requiera algo más háganmelo saber. "Crear" en views.py class RemisionCreateView(CreateView): model = Remision form_class = RemisionForm template_name = 'remision/create.html' success_url = reverse_lazy('erp:remision_list') url_redirect = success_url @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): data = {} cur = db.cursor() try: action = request.POST['action'] if action == 'search_products': data = [] ids_exclude = json.loads(request.POST['ids']) prods = Producto.objects.filter(nombre__icontains=request.POST['term']) for i in prods[0:10]: cur.execute( 'SELECT dt.id , l.codigo FROM erp_detlote dt, erp_lote l WHERE dt.lote_id = l.id AND dt.producto_id=' + str( i.id) + ';') r = cur.fetchall() cont = 0 lotes = [] for c in r: lotes.append(str(c[0]) + " , " + c[1]) cont += 1 item = i.toJSON() item['value'] = i.nombre item['lotes'] = lotes data.append(item) elif action == 'add': with transaction.atomic(): rem = json.loads(request.POST['rem']) remision = Remision() … -
Read an image from a form and then exract the title with tesseract
this is my HTML in a Django project: <form method="GET"> <div> <label for="image"></label> <input type="file" name="image" id="image" required/> </div> <input type="submit" value="Submit"/> </form> and this is the code in views.py to get the image from the form : def home(request): result = None if request.method == 'GET': data = request.GET im = request.FILES.get('image') medecine = ocr_title(im) and I finally this is the code to extract the title (OCR I tested in Jupiter and it works for me) : def ocr_title(im): image = cv2.imread(im, 0) img = cv2.resize(image, (500, 500)) img = cv2.GaussianBlur(img, (5, 5), 0) img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 4) himg, wimg = img.shape maxw = 0 title = pytesseract.image_to_data(img, config='--psm 6 --oem 3') for x, b in enumerate(title.splitlines()): if x != 0: b = b.split() if len(b) == 12 and len(b[11]) >= 4: if (int(b[8]) > maxw): maxh = int(b[9]) maxx = int(b[6]) maxy = int(b[7]) maxw = int(b[8]) text = b[11] return (text) but after that, I end up having errors maybe I didn't get the image correctly -
How to check for cookies in a template tag
I tried this: {% if request.COOKIE['register'] %} ... {% endif %} But I get this error: TemplateSyntaxError at / Could not parse the remainder: '['register']' from 'request.COOKIE['register']' How can I check for a cookie from a template? -
Django: values: how to call model methods
I have a model: class Parcel(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE, null=True) fruit = models.ForeignKey(Fruit, on_delete=models.CASCADE, null=True) quantity = models.IntegerField() class Fruit(models.Model): name = models.CharField(max_length=30) def somemethod(self): if self.name == "apple": return "hurry" else: return self.name Now how can get the somemethod values also in Parcel.objects.values('fruit__name','fruit__somemethod') -
DRF and oauth2: How to infer the user_id from oauth2 access token?
I have the following model: class Posts(models.Model): title = models.CharField(max_length=100) body = models.CharField(max_length=255) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Using this model, when I add a post, I need to specify user_id: nick_user_id = 6 headers = {'Authorization': 'Bearer '+str(Nick_token)} record = {'title': 'Move to cloud?', 'body':'Thinking of moving server to cloud - is this a good idea?','user_id':nick_user_id} Nick_response = requests.post(posts_url, headers=headers, data=record) As you can see, I already have the user's oauth2 token Nick_token which is used in the header of the post request. Is it possible to make the post without needing to specify user_id, instead using the oauth2 access token to automatically infer who the user is? If so, how should I go about this? -
How to apply path-based middleware in Django Channels?
I currently have the problem, that I need different authentication mechanisms for different Django Channel consumers. One of them should use a custom token middleware while the other should use the standard session-based authentication. How can it be achieved that middlewares can be applied per path? In the standard Django views this is achieved with def process_view(self, request, view_func, view_args, view_kwargs): as shown in this answer. # routing.py application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": TokenAuthMiddleware( URLRouter( [ path( "ws-api/v1/farms/controllers/", ControllerConsumer.as_asgi(), name="ws-controller", ), path("ws-api/v1/graphql/", MyGraphqlWsConsumer.as_asgi()), ] ) ) } )