Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to register users for tests?
Can you help me? I dont know django-ajax well, also I am new in django. I want to register user to Mock test, so I tried to use below codes. I am not able to realise what my mistakes are. model.py class MockTest(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE) bio = models.TextField(null= True, blank=True) is_free = models.BooleanField() fee = models.DecimalField(max_digits=10, decimal_places=2) time_created = models.DateTimeField(auto_now=False,auto_now_add=True) time_start = models.DateField(auto_now=False, auto_now_add=False, default='') speak_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) registerations = models.ManyToManyField(User, blank=True, null=True, related_name='registerations') def save(self, *args, **kwargs): # new if not self.slug: self.slug = slugify(self.name) return super().save(*args, **kwargs) def __str__(self): return self.name def get_absolute_url(self): return reverse("teacher:mock_view", kwargs={"slug": self.slug}) def total_registers(self): return self.registerations.count() def is_registered(self,request): return self.registerations.filter(id=request.user.id).exists() views.py def register(request): if request.method == 'POST': user = request.user slug = request.POST.get('slug', None) mock = get_object_or_404(MockTest, slug=slug) if mock.registerations.filter(id=user.id).exists(): massage = "You are already registered" else: mock.registerations.add(user) massage = "succes" cxt = {'total_registers': mock.total_registers, 'massage':massage} return HttpResponse(json.dumps(cxt), content_type='application/json') urls.py path('register/', register, name='register') html <input type="button" id="register" class="" name="{{ mock.slug }}" value="Register" /> <script> $('#register').click(function(){ $.ajax({ type: "POST", url: "{% url 'student:register' %}", data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response) { alert(response.message); alert('Registered people now ' + response.total_registers); … -
Python Django User Membership
I am making an online education website (similar to Lynda.com). I just need the code that enables me to grant access - manually - to users who send me cash money. I'm writing my code using Python Django. Would you help me do it. Thank you. -
How to transfer the data of Arduino to Django app remotely
I'm building a project on Django with Arduino devices connected to it. Do I need an MQTT to transfer data from arduino to django app? or I can use arduino itself to transfer data to django app and btw the arduino is almost 50 meters away from the computer where the django app runs. I'm using Postgresql as Database. -
Django: how to create custom login page with token bases in DjangoRestAPI?
how to create custom login page with token bases in DjangoRestAPI? -
can't send signals to a specific user
i'm sending notifications to a user via django notifications. And i have username regex working on the html so anyone comments with @username it will post and the html is linkable so click on the @username it will take him to the username profile page. Now i am using django signals to match the username and print out the username. but when i use notify to send the notification. it does not work. models.py: class Comment(models.Model): post = models.ForeignKey(post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE) reply = models.ForeignKey('Comment', null=True, related_name='replies', on_delete=models.CASCADE) content = models.TextField() image = models.ImageField(upload_to='comments-pics', null=True, blank=True) voice_record = models.FileField(upload_to='voice-comments', null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__ (self): return '{}.{}'.format(self.post.title, str(self.user.username)) def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) def Comment_save_receiver(sender, instance, created, *args,**kwargs): if created and not instance.parent: user_regex = r'@(?P<username>[\w.@+-]+)' m = re.search(user_regex, instance.content) if m: try: recipient = User.objects.get(username=m.group('username')) except (User.DoesNotExist, User.MultipleObjectsReturned): pass else: notify.send(instance.user, recipient=recipient, actor=instance.user, verb='mention you in a post', target=instance, nf_type='tagged_by_one_user') post_save.connect(Comment_save_receiver, sender=post) -
Django Rest Framework: Pickle Response
What I'm trying to do is build a custom version of cache_page where I have more control over the cache key, but I'm getting stuck with even the basic caching of my response: from django.core.cache import cache class BaseViewSet(viewsets.GenericViewSet): queryset = models.Items.objects.all() def get_queryset(self): return models.Items.objects.all() def list(self, request, **kwargs): response = Response({}) cache.set('test', response, 10) return response Where the relevant parts of my settings.py are setup as: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', ], 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning' } CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": f"redis://127.0.0.1:6729/1", }, } When I try to call the endpoint I get: django.template.response.ContentNotRenderedError: The response content must be rendered before it can be pickled. Then if I change the line to: cache.set('test', response.render(), 10) I get: AssertionError: .accepted_renderer not set on Response Despite the fact that the API call itself works fine without the caching. cache_page actually works fine, so I know it's possible to cache the response, but I can't figure out what I'm missing. -
DRF how can I return only the first serialized object to the view?
in DRF, is there any way to get a single nested image to show up in a view. In my example you can see that there are 2 photos listed. What would be the best solution to retrieve and display just that first photo? This view would be for a list of houses, and I don't want every pic to be displayed, as there could be some users uploading 30+ photos. "url": "http://127.0.0.1:8000/api/v1/listings/1/", "address": "8753 sherwood dr apt 111", "image_set": [ { "photo": "http://127.0.0.1:8000/media/listing_images/front-view.png" }, { "photo": "http://127.0.0.1:8000/media/listing_images/image34453.png } ] }, class ImageSerializerForListingDetail(serializers.ModelSerializer): photo = serializers.ImageField(use_url=True, allow_empty_file=True) class Meta: model = Image fields = ('photo', ) def get_image_url(self, listing): return listing.photo.url class ListingListSerializer(serializers.HyperlinkedModelSerializer): photo = ImageSerializerForListingDetail(many=True, required=False) class Meta: model = Listing fields = ('url', 'address', 'photo', ) class ListingViewSet(viewsets.ModelViewSet): queryset = Listing.objects.all().order_by('id') permission_classes = [IsOwnerOrReadOnly, ] serializer_classes = { 'list': ListingListSerializer, 'retrieve': ListingSerializer } default_serializer_class = ListingSerializer def get_serializer_class(self): return self.serializer_classes.get(self.action, self.default_serializer_class) def create(self, request, *args, **kwargs): serializer = ListingSerializer(data=request.data, files=request.FILES) 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) -
how do I print queryset dictonary in django template
How do I print the below for loop (last for loop) which is printing all prods in my template? I tried to find answers but I'm nowhere close to finding one. Please help me solve this issue. allProds = [] catalogs = Catalog.objects.all().distinct().order_by('name') categories = Category.objects.all().distinct().order_by('name') for catalog in catalogs: allProds.append(catalog) for category in categories.filter(catalog_name=catalog.id): allProds.append(category) products = Product.objects.values('name','image') .filter(category_name=category) allProds.append(products) for p in range(len(allProds)): print(allProds[p]) -
How can automatically Increase the serial number when user register and i want to dsable some content after some seats filled?
How will i get increment in serial number instantly after new register enter ? How should one disable the registration automatically when the seats are filled ? Now I want to increase the number by 1 for each register. Forms.py from django import forms from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User CHOICES = [ ('',''), ('CT', 'Computer Technology'), ('BCA', 'Bachelor of Computer Application'), ('SS', 'Software Systems'), ('CS','Computer Science'), ('IT','Information Technology'), ('DA','Data Analytics'), ] COURSE = [ ('',''), ('Python','Python'), ('Java','Java'), ('C++','C++'), ] class Registerform(UserCreationForm): username = forms.CharField(label="Roll No",help_text="Enter Valid RollNo") name = forms.CharField(label="Candidate Name", max_length=150) dob = forms.DateField(label="Date of Birth",help_text="MM/DD/YY") email = forms.EmailField(help_text="Enter valid Mail") department=forms.CharField( label="Department", widget=forms.Select(choices=CHOICES)) edc = forms.CharField( label="EDC", widget=forms.Select(choices=COURSE)) password1 = None password2 = None class Meta: model = User fields = ["username","name", "dob", "email","department","edc"] Models.py from django.db import models from django.utils.translation import gettext as _ # Create your models here. class listing(models.Model): username = models.CharField(max_length=150) name = models.CharField(max_length=150) dob = models.DateField() email = models.EmailField() department=models.CharField(max_length=150 ) edc = models.CharField(max_length=300,default="") password1=None password2=None def __str__(self): return self.username I want to show my serial number(It want to incremented automatically) here how can I do this? The serial number also want to store in … -
Need some explanation of django code for model manager
I am following a Django project found on Github. Almost understand everything apart from following model manager. Especially the get_releted_products method. Could you please describe how it will work to get the related product from categories. It will be nice if you also send some documentation that can explain this code as well as the StackOverflow forum. class ProductManager(models.Manager): def all(self,**kwargs): #active return self.filter(active=True,**kwargs) def get_related_products(self,instance): qs1 = self.all().filter(categories__in=instance.categories.all()) qs2 = self.all().filter(default=instance.default) return (qs1 | qs2).exclude(id=instance.id).distinct() class Product(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=500,blank=True,null=True) price = models.PositiveIntegerField() active = models.BooleanField(default=True) categories = models.ManyToManyField('Category',blank=True) default = models.ForeignKey('Category',related_name='default_category',blank=True, null=True,on_delete=models.CASCADE) slug = models.SlugField(max_length=48) objects = ProductManager() -
Django - Correct method of consuming my own REST API internally in the views.py?
I created a Django REST API using serializers, viewsets and routers. My end points looks something like this: http://www.website.com/api/items http://www.website.com/api/items/available serializer.py (omitting imports) class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' viewsets.py (omitting imports) class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer @action(methods=['GET'], detail=False) def most_expensive(self, request): query = self.get_queryset().order_by('price').last() serialized = self.serializer_class(query) return Response(serialized.data) Now I want to able to access this API from my views.py to render the HTML with the available items: This is the way im doing it right now: views.py (omitting imports) class ProductListView(View): template = 'store/product_list.html' def get(self, request): items = requests.get('http://127.0.0.1:8000/api/items/available') context = {'items': items} return render(request, self.template, context=context) Using the requests modules I have a couple of concerns, after measuring I noticed there is a 0.015 second delay for that request to go through and if I ever change the API endpoint I would have to adjust it here since its hard coded. I can get my items using: Item.objects.filter(available=True) Which gives me the result pretty much instantly but I'm writing all the queries twice (once in my API and once in my views.py) Is there a better way of doing this like calling the viewset class directly and getting … -
Python: algorithm deos not works
I want to extract data of django.po file (internationalization) in xls (to discuss with non IT project manager) so first, I want to code a function that will extract lines of django.po in a list of tuples (don't know if it is the easiest way but...) and after, I will use xlwt export data in xls files (each tuple will be written in a line) translation.txt #: .\myproject\settings.py:1 #: .\myproject\settings.py:2 msgid "English" msgstr "Anglais" #: .\myproject\settings.py:3 msgid "French" msgstr "Français" expected result : liste of 2 tuples [ (#: .\myproject\settings.py:1,#: .\myproject\settings.py:2,msgid "English",msgstr "Anglais"), (#: .\myproject\settings.py:3,msgid "French",msgstr "Français"), ] current result : second tuple missing [ (#: .\myproject\settings.py:1,#: .\myproject\settings.py:2,msgid "English",msgstr "Anglais") ] function def translation(): fichier_traduction = r"C:\Users\translation.txt" file = open(fichier_traduction, newline='', encoding='utf-8') reader = csv.reader(file) liste = [] tuple = () for row in reader: if len(row) > 0: tuple = tuple + (row[0],) else: liste.append(tuple) tuple = () return liste -
Dajngo-alluth override signup method in customform
i have a trouble with django-allauth. I create my customform and it works fine, but now i need to override the signup i tried this: class CustomSignupForm(SignupForm): password1 = SetPasswordField(label="Password") password2 = PasswordField(label="Conferma Password") first_name = forms.CharField(max_length=30, label='Nome') last_name = forms.CharField(max_length=30, label='Cognome') data_di_nascita = forms.CharField(max_length=30, label='Data di nascita',widget=forms.TextInput(attrs={'placeholder': 'gg/mm/aaaa'})) citta = forms.CharField(max_length=30, label='Città', required=False) regione = forms.CharField(max_length=30, label='Regione', required=False) stato = CountryField(blank_label='Nazione',blank=True).formfield() termini_e_condizioni = forms.BooleanField(label='termini_e_condizioni',widget=forms.CheckboxInput(attrs={'class':'your_class'})) privacy = forms.BooleanField(label='privacy',widget=forms.CheckboxInput(attrs={'class':'your_class'}), required=False) newsletter = forms.BooleanField(label='newsletter',widget=forms.CheckboxInput(attrs={'class':'your_class'}), required=False) def __init__(self, *args, **kwargs): super(CustomSignupForm, self).__init__(*args, **kwargs) self.fields['password1'].label = "Password" self.fields['password2'].label = "Conferma Password" self.fields['password1'].widget = PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}) self.fields['password2'].widget = PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Conferma Password'}) for field in self.fields: help_text = self.fields[field].help_text self.fields[field].help_text = None if help_text != '': self.fields[field].widget.attrs.update({'class':'has-popover', 'data-content':help_text, 'data-placement':'right', 'data-container':'body'}) def confirm_password(self): print('entered confirm_password') if ("password1" in self.cleaned_data and "password2" in self.cleaned_data): print('password fields found') if self.cleaned_data['password1'] != self.cleaned_data['password2']: print('le password non corrispondono') raise forms.ValidationError(_("You must type the same password" " each time.")) print('passwords equal') return self.cleaned_data["password1"] else: print('passwords not found in form') raise forms.ValidationError(_("Password not found in form")) def signup(self, request, user): print("-------------------------------------------------------------------OK----------------------------------------------") user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() userpost=User.objects.get(username=self.cleaned_data['username']) userpost.personal_data.birthdate = self.cleaned_data['data_di_nascita'] userpost.personal_data.country = self.cleaned_data['stato'] userpost.personal_data.subcountry = self.cleaned_data['regione'] userpost.personal_data.city = self.cleaned_data['citta'] userpost.personal_data.created = timezone.now() userpost.personal_data.save() userpost.markeringpreference.subscribed=self.cleaned_data['newsletter'] userpost.newsletterpreference.subscribed=self.cleaned_data['newsletter'] userpost.markeringpreference.save() userpost.newsletterpreference.save() … -
How to set boolean fields of all but one from the multiple Django formset rows during save
I am updating multiple records from a single form using Django inline formset factory. Multiple number of rows of data are expected to be created by users at once. My model is: class Tariff(models.Model): tariff_item = models.AutoField(primary_key=True, verbose_name='Tariff Item') eff_date = models.DateField(null=True, verbose_name='Eff date') tariff_rate = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, default=0.00, ...) tariff_is_past = models.BooleanField(default=False) As stated above there can be more than one formset row when the user saves it. The only caveat being: All the rows with data MUST be marked with BOOLEAN FIELD "tariff_is_past" to True, except the last. Presently the boolean fields are being marked manually. As the rows are as yet not part of the table I can not run a query on the rows and set the boolean field to True. Can the scenario be addressed? Can I set Boolean field "tariff_is_past" for all but the last (ordered on the date field "eff_date") row? -
check for presence in queryset in DTL django
I am creating a to do list. I want to display the tasks if the user has any. If not, then display something else. I kept the design simple. <h2>Here is the list of tasks! Start working!</h2> {% if obj in task %} <ul> {% for obj in task %} <li>{{ obj }}</li> {% endfor %} </ul> {% else %} <p>You dont have anything on this list yet!</p> {% endif %} The 'task' is the queryset and currently consists of 2 objects. But none of them are being displayed. Everything was working fine before I tried to apply the presence check. Now it just jumps to that else statement. views.py: def task(request): task = Task.objects.filter(user=request.user) queryset = task.order_by('-start_date') context = { 'task': queryset, } return render(request, 'task-list.html', context) -
get specific field data from another table using forignkey in django
i have a table in models.py with class name registration and another table profileimage with foreignkey relation with registration model now i want to get verify the email address by using profileimage table models.py class Registration(models.Model): YourName = models.CharField(max_length=30) Email = models.EmailField(max_length=254,verbose_name='email') password = models.CharField(max_length=254,verbose_name='password',null=True) PhoneNumber = models.IntegerField(null=True,verbose_name='email') CompanyName = models.CharField(max_length=30) WebSiteName = models.CharField(max_length=30) NumberOfEmplyes = models.IntegerField(null=True) YourRoleInCompany = models.CharField(max_length=100) SoftwareUsedBefore = models.CharField(max_length=30) Turnout2017 = models.IntegerField(null=True) Turnover2016 = models.IntegerField(null=True) Description = models.CharField(max_length=30) ClientArgument = models.CharField(max_length=2000,null=True) PaymentsPlan = models.CharField(max_length=100,null=True) class ProfileImages(models.Model): MemeberName = models.OneToOneField('Registration',on_delete=models.CASCADE,blank=True) profile_image = models.ImageField(upload_to='media/profile_image',default=True,null=True) def __str__(self): return "user profile image" now for example i have email adress which i get from sessions now e.g example@stack.com now i want to use this email to fillter record in this way. profile_image= ProfileImages.objects.filter(Registration__Email=email).select_related() let me know what is the exact way to perform this query -
django : Show only extra row in tabularinline
I'm using django tabular inline to add transactions related to the client. but I don't want to see the previous transactions, I just want an extra empty row. class TransactionInline(admin.TabularInline): model = Transaction extra = 1 #max_num = 1 but still it's showing the last inserted transaction. -
Using Swagger with Django Rest Framework, can I see POST parameters in different fields instead of one body
I'm actually create APIs on a Django Website using Django Rest Framework. I'm trying to document them using Swagger. I'm using Django 2.1, django-rest-swagger 2.2 and djangorestframework 3.11 Everything is nearly working as expected except something : Let me explain you : I have this model (models.py) class Technology(models.Model): """ This model defines the different technologies """ name = models.CharField(max_length=CHAR_SHORT) path = models.CharField(max_length=CHAR_SHORT, validators=[validate_tech_path], help_text='this is only used to construct the url') image = models.ImageField() mailer = models.EmailField(blank=True) external = models.BooleanField(default=False) internal = models.BooleanField(default=False) class Meta: verbose_name_plural = "technologies" ordering = ['name'] def __str__(self): return self.name Then I have the corresponding serializer class (serializer.py): class TechnologySerializer(serializers.ModelSerializer): """ This model defines the different technologies """ class Meta: model = Technology fields = ('id', 'name', 'path', 'image', 'mailer', 'external', 'internal') Finally I have my view with generated APIs (views.py): class TechnologyViewSet(viewsets.ModelViewSet): queryset = Technology.objects.all() serializer_class = TechnologySerializer http_method_names = ['get','post','delete','put'] Here's the result : Api description 1 Api description 2 As you see on the picture above, the parameters are une the json body. Is it possible to have something like this for all the parameters : API parameter wanted Thanks a lot. -
Python Django Display Nested Objects
Hi I'm new to django rest framework and I'm trying to serialize 3 nested models. The relationships are: hotel_social_media_type has a one to many relationship to hotel_social_media and hotel has one to many relationship to hotel_social_media. Right now I can only serialized hotel to hotel_social_media but I can't serialize hotel_social_media_type. Here's my serializers: class SocialMediaTypeSerializer(serializers.ModelSerializer): """Serializes social media type""" class Meta: model = models.SocialMediaType fields = ('name', 'icon', 'icon') class HotelSocialMediaSerializer(serializers.ModelSerializer): """Serializes media files""" hotel_social_media_type = SocialMediaTypeSerializer(many=False, read_only=True) class Meta: model = models.HotelSocialMedia fields = ('url', 'hotel_social_media_type') class HotelSerializer(serializers.ModelSerializer): """Serializes Restaurat, Bars, TouristInformation and Tourist Spots """ hotel_images = HotelImageSerializer(many=True, read_only=True) hotel_social_media = HotelSocialMediaSerializer(many=True, read_only=True) class Meta: model = models.Hotel fields = ('id', 'name', 'hotel_images', 'hotel_social_media') Current result is: { "id": 1, "name": "Alta Vista", "hotel_images": [ { "id": 1, "name": "Alta Vista", "path": "http://127.0.0.1:8000/media/images/hotel-1.jpg" } ], "hotel_social_media": [ { "url": "https://www.facebook.com/abscbnNEWS" } ] } What I want is: { "id": 1, "name": "Alta Vista", "hotel_images": [ { "id": 1, "name": "Alta Vista", "path": "http://127.0.0.1:8000/media/images/hotel-1.jpg" } ], "hotel_social_media": [ { "url": "https://www.facebook.com/abscbnNEWS", "hotel_social_media_type": { "name": "Facebook", "icon": "http://127.0.0.1:8000/media/images/fb-1.jpg" } } ] } hotel_social_media must also display hotel_social_media_type -
django use slug not pk
I'm trying to use slug in my url, I've done this fine on other sites but for some reason, I am unable to use slug in a url on this area of the site, only the primary key gets the desired result, what am i missing here? The only difference from the other sites I have done is that the slug will be used for filtering which is what I think is messing this up. Model: class Desk(models.Model): name = models.CharField(max_length=16, unique=True) slug = models.SlugField(max_length=16, unique=True) def __str__(self): return self.slug class Handover(models.Model): desk = models.ForeignKey( Desk, related_name="handover", on_delete=models.CASCADE ) published = models.DateTimeField(auto_now_add=True) user = models.CharField(max_length=45) ongoing = models.CharField(max_length=1024, null=True, blank=True) resolved = models.CharField(max_length=1024, null=True, blank=True) planned_work = models.CharField(max_length=1024, null=True, blank=True) heightened_awareness = models.CharField(max_length=1024, null=True, blank=True) In the views below, for some reason I can't use the word 'slug' in the filter, it just throws an error. The current setup works if I use the PK in the url in the browser, but not the slug which is what I want to use, (I'm not sure why this works either, I would expect this not to work because of using 'slug' in the url). Here is the view: class IndexView(ListView): template_name … -
Django, Materialize, Django-tables2: Expected table or queryset, not str
I have a form and one of the fields is a MultipleChoiceField. The form is rendered in a modal using Materialize. I had issues to render the choices in the form but found this answer I changed the field to: comp = forms.MultipleChoiceField(choices=COMP, widget=forms.Select(choices=COMP, attrs={'class': 'browser-default'})) which solved the rendering issue. Once I submit the form I expect to view the data in the django-tables2 table, which worked fine, but now I receive the following error: Exception Value: Expected table or queryset, not str If I remove the widget the form doesn’t render as I would like but I’m able to submit the form and see the data in the table. What am I missing? How can I resolve this? Please let me know if I should post additional code, thank you -
live countdown in django keith wood countdown timer
I am using keith wood countdown, How do i set the (14 days) countdown when after the user login, and the countdown will still be redundant even if the user logout or leave the page? <div id="defaultCountdown"></div> <script> $(function () { var days = 14 var austDay = new Date(); austDay = new Date(austDay.getDate() + 1, 1 - 1, 26); $('#defaultCountdown').countdown({until: austDay}); $('#year').text(austDay.getFullYear()); }); </script> this is my views.py def profile(request): if request.method != 'POST': raise Http404('Only POSTs are allowed') try: m = User.objects.get(username=request.POST['username']) if m.password == request.POST['password']: aa = request.POST['username'] request.session['member_id'] = m.id print(m.id) return render(request, 'profile.html') except User.DoesNotExist: messages.Warning(request, 'Incorrect Username or Password.') return render (request, "login.html") -
Django 3 - doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am learning Django 3 but having a problem. My app is called calc1. Code below: MODELS.PY from django.db import models # Create your models here. class Dreamreal(models.Model): website = models.CharField(max_length = 50) mail = models.CharField(max_length = 50) name = models.CharField(max_length = 50) phonenumber = models.IntegerField() class Meta: db_table = "dreamreal" VIEWS.PY from django.shortcuts import render from django.http import HttpResponse import datetime import time from .models import Dreamreal from django.http import HttpResponse # Create your views here. def home(request): today = datetime.datetime.now().date() return render(request, 'home.html',{'today' :today}) def crudops(request): dreamreal = Dreamreal( website = "www.vlcbt.org.uk", mail = "info@vlcbt.org.uk", name = "John", phonenumber = "08767655665" ) dreamreal.save() # read all entries and print objects = Dreamreal.objects.all() res ="printing all documents <br>" for elt in objects: res += elt.name +"<br>" return HttpResponse(res) When I try to migrate I get the following error message: File "C:\Users\john\Envs\lms\Scripts\projects\jkjlms\calc1\urls.py", line 3, in from . import views File "C:\Users\john\Envs\lms\Scripts\projects\jkjlms\calc1\views.py", line 5, in from .models import Dreamreal File "C:\Users\john\Envs\lms\Scripts\projects\jkjlms\calc1\models.py", line 5, in class Dreamreal(models.Model): File "C:\python\lib\site-packages\django\db\models\base.py", line 115, in new "INSTALLED_APPS." % (module, name) RuntimeError: Model class calc1.models.Dreamreal doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Thanks for your help in advance -
Django Send Request Like Postman
I want to get data from a web service. For this use the following URL on Postman: http://x.x.x.x:8090/api/jserv.ashx?action=ReportMethod // has a paramater And I have to add a raw like the following to verify user: { "user": { "userid": "xxxx", "username": "User", "status": "false", "mesaj": "null", "no": 0, "versiyon": "null" }, "start": "1900-01-01T00:00:00", "end": "2020-02-25T00:00:00" } When I use Postman I can get data. How to do this operation using Django? -
how can i get the user commented on a specific course from database? where as i have a relation with of courses to comments and user to comments
this is my code so i want to ask for your help... i'm using by default User model of django and having different courses having comments by different users so i want to get all the comments on specific course by all the users using just course_id. model.py class Course(models.Model): course_id = models.CharField(max_length=20 , auto_created= True) course_name = models.CharField(max_length=250) course_pic = models.ImageField(upload_to='images' , blank=True) course_author = models.CharField(max_length=15) released_date = models.DateTimeField( auto_now_add=True) course_rating = models.CharField(max_length=15) class Comments(models.Model): course = models.ForeignKey(Course,on_delete=models.CASCADE,related_name='comments') commented_by = models.ManyToManyField(User) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_on'] def __str__(self): return self.body views.py def CourseDetail(request, id): course = Course.objects.get(course_id = id) comments = Comments.objects.filter(course_id = id) print(comments) if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.course = course new_comment.save() comment_form = CommentForm() else: comment_form = CommentForm() context ={ 'course': course, 'comments': comments, 'comment_form': comment_form } return render(request, 'pages/course_details.html', context)