Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
facebook's sharer.php shows 403 Forbidden in share box
I am using this for sharing on Facebook. <meta property="og:image" content="https://url.com/{{ article.img_path }}"> <meta property="og:type" content="website"/> <meta property="og:title" content="{{ article.title }}"/> <meta property="og:description" content="{{ article.title }}"/> <meta property="og:url" content="https://url.com/{{ article.path }}"/> . . <a href="https://www.facebook.com/sharer/sharer.php?u=https://url.com/{{ article.path | urlencode }}"> <i class="fa fa-facebook-square fa-2x"></i> </a> I also get a 403 Forbidden in the box. Default is mobile view even on Desktop ? -
How to create invoice depending upon template give by User in django
I am making a web application built on django which has a feature of Invoice which should be downloadable. I want that invoice to be created depending upon the template provided by User. Eg: If a doctor uses my application he can upload the template of his medical clinic and whenever we generate invoices of patients for medicines all the invoice generated for prescribed medicines must be downloadable in that template. Please help me -
how to change EmailValidator Error Message
models.py class User(AbstractBaseUser): email = models.EmailField( verbose_name='Email', max_length=255, unique=True, error_messages={'msg':"Enter a valid Email Address"}, ) name = models.CharField(max_length=200) phone_number= models.CharField(max_length=200, blank=True) address= models.CharField(max_length=200, blank=True) tc = models.BooleanField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'tc'] serializer.py class UserRegistrationSerializer(serializers.ModelSerializer): # We are writing this becoz we need confirm password field in our Registratin Request password2 = serializers.CharField(style={'input_type':'password'}, write_only=True) class Meta: model = User fields=['email', 'name' ,'phone_number', 'address','password', 'password2','tc' ] extra_kwargs={ 'password':{'write_only':True}, } def validate(self, attrs): password = attrs.get('password') password2 = attrs.get('password2') if password != password2: raise serializers.ValidationError("Password and Confirm Password doesn't match") return attrs def create(self, validate_data): return User.objects.create_user(**validate_data) Output i am getting when i put an invalid email id { "email": [ "Enter a valid email address." ] } Expected Output { "msg": "Enter a valid email address." } I have used error_message in models to get the output i want and i have also used EmailValidator(message="") but nothing is working. I tried to use def clean_email in serializers.py but that also didn't worked. please help -
ERROR: TypeError at /admin/myapp/booking/19/change/
I've created a model using an abstract user model class for Online flight ticket booking. I'm new to this so haven't added many functionalities to it. I'm sharing my model.py, admin.py, serializer.py, views.py. My question: In the link below shows a screenshot of an error occurring while I want to GET PUT DELETE booking data using ADMIN panel. I'm not able to figure out the problem yet. Error while trying to GET PUT DELETE booking #models.py import email from pyexpat import model from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) class UserManager(BaseUserManager): def create_user(self, email, name,contact_number,gender,address,state,city,country,pincode,dob ,password=None, password2=None): if not email: raise ValueError('User must have an email address') user = self.model( email=self.normalize_email(email), name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name,contact_number,gender,address,state,city,country,pincode,dob , password=None): user = self.create_user( email, name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, password=password, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = … -
when i am django date filter not working?
This is my query : I given the below dates: startdate : 2022-06-06 enddate : 2022-06-07 user=Model.objects.filter(agent=fullnames['username']).filter(status=ticket_status)).filter(completed_date__gt=startdate,completed_date__lt=enddate) output: after filter the query im getting this output , in this 2022-06-08 not required, but it is showing { "reference": "9802047093", "name": "Caliber", "completed_date": "2022-06-07" }, { "reference": "9802510868", "name": "Caliber", "completed_date": "2022-06-06" }, { "reference": "9738614446", "name": "Caliber", "completed_date": "2022-06-08" } -
Django: [Errno 2] No such file or directory: '/tmp/tmpmhi9gua5/texput.pdf' during generate a pdf
I need some help please, Hi for all here am trying to generate a pdf with latex in my django applicaton but i keep see an error when i add a specific data in my template-latex.tex. This is my views.py: if request.user.is_authenticated: if request.method == 'POST': form = ReportForm(request.POST, ) form.instance.user=request.user if form.is_valid(): form.save() obj_Formulaire = MyModel.objects.filter(user=request.user).last() field_obj_load_between_posts = MyModel._meta.get_field('load_between_posts') field_value_load_between_posts = field_obj_load_between_posts.value_from_object(obj_Formulaire) load_between_posts = field_value_load_between_posts if load_between_posts == True: field_obj_custom_load = MyModel._meta.get_field('custom_load') field_value_custom_load = field_obj_custom_load.value_from_object(obj_Formulaire) qh = float(field_value_custom_load) else: qh = float(0) #----some other code about getting the value fields---- w_profile = float(sizes_column_wprofile) w_project = round(float((1.5 * qh * distance * height) / fy),2) if w_profile >= w_project: resultat_mechanical = "Wprofile={0} > Wproject={1}".format(w_profile, w_project) resultat_resistance_criteria = "Profile Verified ✔" else: resultat_mechanical = "Wprofile={0} < Wproject={1}".format(w_profile, w_project) resultat_resistance_criteria = "Profile Not Verified" context = { 'qh': qh, 'resultat_resistance_criteria': resultat_resistance_criteria, 'resultat_mechanical' : resultat_mechanical } template = get_template('pages/my_latex_template.tex') rendered_tpl = template.render(context).encode('utf-8') # <3> with tempfile.TemporaryDirectory() as tempdir: # <4> for i in range(2): process = Popen( ['pdflatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') # <5> r.write(pdf) return r form = ReportForm() context = {'form': form} return render(request, 'pages/form_gelander_report.html', context) everything … -
Cannot open any page when implemented next parameter in Django 3.2
I am using Django 3.2. I have my custom LoginView and I'd like to implement the next parameter so if somebody will try to access the page where login is required then after log-in it will redirect the user to this page. I have seen many solutions but they are old and I cannot implement them in my code. views.py class UpdatedLoginView(LoginView, CategoryMixin, TagMixin): form_class = LoginForm template_name = 'user/login.html' redirect_field_name='main/homepage.html' def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): if 'next' in request.POST: return redirect(request.POST.get('next')) else: return(redirect('homepage')) else: return render(request, self.redirect_field_name, {'form': form}) class HomePageView(LoginRequiredMixin, TemplateView): template_name = "main/homepage.html" login.html <form method="post" novalidate> {% csrf_token %} {{ form|crispy }} {% if request.GET.next %} <input type="hidden" name="next" value="{{ request.GET.next }}"/> {% endif %} <button type="submit">Login</button> </form> settings.py LOGIN_REDIRECT_URL = 'homepage' LOGOUT_REDIRECT_URL = 'login' The problem with my solution is that it redirects me to homepage but once I click on any hyperlink it redirects me to login page again and the url looks like this: http://127.0.0.1:8000/?login=/article_list/ In all my views I am using LoginRequiredMixin mixin. How can I fix this issue? -
Django tests self.client.post using wrong url
I have a test which throws a NoReverseMatch exeption. In the test I define the url add_collection_url = reverse('add-cc-collection', args=[client.code, order.code]) and I can check that the url is found print(add_collection_url) which finds the correct url /crm/clients/A00001/order/O00001/add-cc-collection/ However, on the next line I post to the url response = self.client.post(add_collection_url, {'order': order.id, 'deadline': deadline, 'instructions': "Some instructions etc"}) and this line throws the exception django.urls.exceptions.NoReverseMatch: Reverse for 'add-collection' not found. 'add-collection' is not a valid view function or pattern name. note the reference to 'add-collection', which was the name of the url before I changed it to 'add-cc-collection'. When I run the server everything works as it should, it's just the test which throws the exception. My guess is something weird happening with caching but, for what it's worth I make sure to cache.clear() in TestCase tearDown -
Django model with multiple inheritance raises 'django.core.exceptions.FieldError' exception on delete
I am using django 3.2. I am writing a social app, which necessitates (makes necessary) the use of multiple inheritance. I am having a problem with one of the inheritable models, in that when I inherit from that model, I can't delete instances of the derived (child) class. Code (relevant parts only): class Actionable: def __init__(self, *args, **kwargs): self.owner = None self.owner_id = None self.actionable_object = None self.ct = None self.object_id = None self.is_setup = False def setup_variables(self, args): if not self.is_setup: self.owner = args['owner'] self.owner_id = args['owner_id'] self.actionable_object = args['actionable_object'] self.ct = args['ct'] self.object_id = args['object_id'] self.is_setup = True # This MUST be implemented by ALL CONCRETE sub classes @abstractmethod def get_actionable_object(self): raise NotImplementedError("Subclasses MUST implement get_actionable_object()") # This MUST be implemented by ALL CONCRETE sub classes @abstractmethod def get_owner(self): raise NotImplementedError("Subclasses MUST implement get_owner()") # .... class SocialActivity(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, db_index=True, related_name='%(app_label)s_%(class)s_content_types', related_query_name='%(app_label)s_%(class)s_content_type') object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey('content_type', 'object_id') actor = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s_users', related_query_name='%(app_label)s_%(class)s_user') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"SocialActivity: {self.content_type.name}, {self.object_id}, {self.actor.username}, {datetime.strftime(self.created_at,'%Y-%B-%d %H:%M:%s')} " class Meta: abstract = True constraints = [ models.UniqueConstraint(fields=['content_type', 'object_id', 'actor'], name="%(app_label)s_%(class)s_user_unique") ] class SocialMediaSharingPlatform(models.Model): name = models.CharField(max_length=64, unique=True) endpoint = models.URLField() post_params = JSONField() … -
Python based web application using Panel/ Dash
I am exploring different python libraries like Panel/ Dash for building an analytics tool. My question is should I consider using a Django framework and then integrating Panel/Dash features in Django? Or, if I have experience with web app development (in JS) can I just go for building the app purely using Panel/ Dash? (I know that there are Django + Dash and pure Dash applications out there; just trying to understand the pros/ cons of these options) Thanks in advance for your answers! -
NameError at / name 'HttpResponce' is not defined
enter image description here enter image description here from django.http import HttpResponse from django.shortcuts import render Create your views here. #i'm trying to print hello world in django but i'm facing error's def fun(request): return HttpResponce("hello world") -
Django: FileNotFoundError: [Errno 2] No such file or directory: 'pdflatex': 'pdflatex' during generate a pdf with latex
i want to generate a pdf with latex in my django application , I have tried this but it gives me an error. This is my views.py: if request.user.is_authenticated: if request.method == 'POST': form = ReportForm(request.POST, ) form.instance.user=request.user if form.is_valid(): form.save() obj_Formulaire = MyModel.objects.filter(user=request.user).last() field_obj_load_between_posts = MyModel._meta.get_field('load_between_posts') field_value_load_between_posts = field_obj_load_between_posts.value_from_object(obj_Formulaire) load_between_posts = field_value_load_between_posts if load_between_posts == True: field_obj_custom_load = MyModel._meta.get_field('custom_load') field_value_custom_load = field_obj_custom_load.value_from_object(obj_Formulaire) qh = float(field_value_custom_load) else: qh = float(0) context = { 'qh': qh, } template = get_template('pages/my_latex_template.tex') rendered_tpl = template.render(context).encode('utf-8') # <3> with tempfile.TemporaryDirectory() as tempdir: # <4> for i in range(2): process = Popen( ['pdflatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') # <5> r.write(pdf) return r form = ReportForm() context = {'form': form} return render(request, 'pages/form_gelander_report.html', context) ----> but it gives me : FileNotFoundError: [Errno 2] No such file or directory: 'pdflatex': 'pdflatex' How i could solve this error. THANKS IN ADVANCE. -
ModuleNotFoundError: No module named 'decouple'
I have a working Django project. If I run it - everything works fine Here is the structure of the project titest_project tibrains_app tools __init__.py load_django.py countries_add.py apps.py models.py load_django.py import sys import os import django sys.path.append('/mnt/HDD/tibrains/03/titest_project') os.environ['DJANGO_SETTINGS_MODULE'] = 'titest_project.settings' django.setup() countries_add.py import load_django from tibrains_app.models import ShopCountry When I run countries_add.py it gives the error - No module named 'decouple'. Though when I run the project itself - it works without errors. What could be the problem? -
Django post_delete instance is still present in the database
One of the keyword argument in he post_delete is the instance, which is the actual instance being deleted. According to the django docs - Note that the object will no longer be in the database, so be very careful what you do with this instance. I am testing the following code -> @receiver(post_delete, sender=Dummy) def post_delete_callback(**kwargs): print('inside post_delete ----------') instance = kwargs.get('instance') raise Exception('Exception from the post delete receiver') But even after the exception, the object should be deleted in the database, but I am getting the exception, as well as the object is not getting deleted from the database. In case of pre_delete signal this is justifiable, but what is with the post_save signal? Am I missing something here? -
Django Sum by category
Sorry if the question has already been asked elsewhere. I have a travel tool. I have my travel model, containing the activity model. Each activity has a category and a price. I would like to add up the prices of the activities for each category, and I admit I am stuck. models.py : class Activity(models.Model): TRANSPORT = 'Transport' HEBERGEMENT = 'Hébergement' RESTAURATION = 'Restauration' LOISIR = 'Loisir' ROLE_CHOICES = ( (TRANSPORT, 'Transport'), (HEBERGEMENT, 'Hébergement'), (RESTAURATION, 'Restauration'), (LOISIR, 'Loisir'), ) category = models.CharField(max_length=30, choices=ROLE_CHOICES) trip = models.ForeignKey(Trip, null=True, blank=True, on_delete=models.SET_NULL) place = models.ForeignKey(Place, null=True, on_delete=models.SET_NULL) date_start = models.DateField(default=date.today) time_start = models.TimeField(auto_now=False, auto_now_add=False, null=True, blank=True) date_end = models.DateField(default=date.today) time_end = models.TimeField(auto_now=False, auto_now_add=False, null=True, blank=True) visitor = models.ManyToManyField(Character) price = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) prepaid = models.BooleanField(null=True) class Meta: verbose_name_plural = "Activities" views.py : def travel_detail(request, travel_id): travel = get_object_or_404(Trip, id=travel_id) activities = Activity.objects.filter(trip_id=travel_id) travellers = travel.traveller.all().order_by("last_name", "first_name") prices = Activity.objects.aggregate(Sum('price')) template = 'travel/travel_detail.html' context = { 'travel': travel, 'activities' : activities, 'travellers' : travellers, 'prices' : prices, } return render(request, template, context) template : {% for price in prices %} {{prices}} {% endfor %} My template returns this for now: {'price__sum': Decimal('43.6000000000000')} -
can we cache count query before request hits django
I have home page which lists from a very large table. It is paginated by PageNumberPagination. The loading time of this page is affected because of the count() query of the paginator. I resolved slowness for all other requests by installing django-cachalot. However the first request still takes up a lot of time. I tried to create a fake request in AppConfig.ready() so that the count() query gets cached every time when the project loads up. But it didn't work. Is there a clean hack for caching the count(*) query before the first request is made? -
JSON decode error JSONDecodeError at /admin/forms/export-entries [closed]
This is code in my views.py file where i am getting error for n in entries: row = [n.id] columns = n.columns.all() for col_id in cols: exist = False for d in columns: if col_id == d.field_id: exist = True row.append(d.value) elif type(col_id) == str: x = col_id.split('_') if int(x[0]) == d.field_id: dic = json.loads(d.info) l_key = '_'.join(x[1:]) if l_key in dic: exist = True row.append(dic[l_key]) I am getting error in this line dic = dic = json.loads(d.info) i am getting entries from my database and making its csv file and give it to user to dowload it from my website -
Authentication in Django Rest framework using django-auth-adfs
I am using the django-auth-afs python library to authenticate and protect my DRF API. I have registered my app in Azure and have client_id, client_secret and tenant_id. Can someone help to tell me how to configure the django rest framework? I have tried out the following documentation https://django-auth-adfs.readthedocs.io/en/latest/rest_framework.html https://django-auth-adfs.readthedocs.io/en/latest/azure_ad_config_guide.html#step-1-register-a-backend-application My current configuration in settings.py AUTHENTICATION_BACKENDS = ( 'django_auth_adfs.backend.AdfsAuthCodeBackend', 'django_auth_adfs.backend.AdfsAccessTokenBackend', ) AUTH_ADFS = { 'AUDIENCE': client_id, 'CLIENT_ID': client_id, 'CLIENT_SECRET': client_secret, 'CLAIM_MAPPING': {'first_name': 'given_name', 'last_name': 'family_name', 'email': 'upn'}, 'GROUPS_CLAIM': 'roles', 'MIRROR_GROUPS': True, 'USERNAME_CLAIM': 'upn', 'TENANT_ID': tenant_id, 'RELYING_PARTY_ID': client_id, } REST_FRAMEWORK = { # type: ignore # disable this until Azure SSO integration done 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'django_auth_adfs.rest_framework.AdfsAccessTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), When to try to access my API I get response back but it should throw Unauthorised message and When I try to access the /admin page I get the following error 022-06-09 08:36:33,718 - INFO - django_auth_adfs - django_auth_adfs loaded settings from ADFS server. 2022-06-09 08:36:33,718 - INFO - django_auth_adfs - django_auth_adfs loaded settings from ADFS server. 2022-06-09 08:36:33,718 - INFO - django_auth_adfs - operating mode: openid_connect 2022-06-09 08:36:33,718 - INFO - django_auth_adfs - operating mode: openid_connect ...... 2022-06-09 08:36:33,719 - DEBUG - django_auth_adfs - django_auth_adfs authentication backend was called … -
Django disable checkboxes in dependent lists
I have 3 lists of checkboxes and I'd like to disable all unnecessary checkboxes in my HTML file if there are no relevant products connected to this product and change the count number dynamically. For now, I managed to display the total number of items per checkbox but I am not sure how to make the count dynamic so if the user chooses checkbox 1 in the team list then numbers in other lists will adjust and show relevant count. If the user selects checkbox 1 in the team list I want to disable all change from this: <input class="form-check-input" type="checkbox" value="{{object.title}}" id="{{object.title}}" data-filter="type"> To this: <input class="form-check-input" type="checkbox" value="{{object.title}}" id="{{object.title}}" data-filter="type" disabled> views.py class Search(LoginRequiredMixin, ListView): login_url = 'login' redirect_field_name = 'login' template_name = 'product-list.html' model = Product queryset = Product.objects.filter(status=1) def get_context_data(self, **kwargs): context = super(Search, self).get_context_data(**kwargs) type = Type.objects.annotate(type_count=Count('type_product', filter=Q(type_product__status=1))) role = Role.objects.annotate(role_count=Count('role_product', filter=Q(role_product__status=1))) leading_team = Team.objects.annotate(team_count=Count('product', filter=Q(product__status=1))) product_list = Product.objects.filter(status=1) context['product_type'] = product_type context['role'] = role context['leading_team'] = leading_team context['product_list'] = product_list return context #Filter data def filter_data(request): type = request.GET.getlist('product_type[]') role = request.GET.getlist('role[]') leading_team = request.GET.getlist('leading_team[]') product_list = Product.objects.filter(status=1) if len(type) > 0: product_list = product_list.filter(type__title__in=type).distinct() if len(role) > 0: product_list = product_list.filter(service_role__title__in=role).distinct() if len(leading_team) … -
Django return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: CsExpert_user
So I am working on a website, and whenever I want to create a new user, I am getting this error, and I don't know what to do next, it seems like tables for my models are not being created, in this case what can I do? my models.py : class User(AbstractUser): pass my views.py: def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "CsExpert/register.html", { "message": "Passwords must match." }) # Attempt to create new user try: user = User.objects.create_user(username, email, password) user.save() except IntegrityError: return render(request, "CsExpert/register.html", { "message": "Username already taken." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "CsExpert/register.html") -
I am getting Error: create_user() missing 1 required positional argument: 'username'
I am creating a Profiles REST API I am getting error on line 30 of serializers.py i.e the password. This is the models.py def create_user(self,email,name,password=None): """Create a new user profile""" if not email: raise ValueError('User must have an email address') email = self.normalize_email(email) # normalize_email() is a helper function that converts email 1st to lowercase user = self.model(email=email,name=name) # self.model is the UserProfileManager class user.set_password(password) # set_password() is a helper function that hashes the password user.save(using=self.db)# save() is a helper function that saves the user to the database return user This the serializers.py class UserProfileSerializer(serializers.ModelSerializer): def create(self,validated_data): """Create and return a new user""" user = models.UserProfile.objects.create_user( email=validated_data['email'], name=validated_data['name'], password=validated_data['password'], ) return user -
How to return only specified fields from serializerMethodField using DRF
it will return nested array like { project_name:test, site_id:[[1],[2]],site_name:[[test1],[test2]] },but I would like to return like this {{sitename:test1, siteid:1},{sitename:test2, siteid:2}} class ProjectSite(models.Model): site_id = models.AutoField(primary_key=True, unique=True) site_name = models.CharField(max_length=200,name='project_site_name') project_id = models.ForeignKey(Project, on_delete=models.CASCADE, blank=True, null=True, related_name="projectid") class Serializer(serializers.ModelSerializer): ... site_ids = serializers.SerializerMethodField(read_only = True) site_name = serializers.SerializerMethodField(read_only = True) ... def get_site_ids(self, obj): return list(obj.projectid.values_list('id').distinct()) def get_site_name(self, obj): return list(obj.projectid.values_list('site_name').distinct()) -
django - relation between server tags, server and the post
I'm creating a reddit clone app, There are 3 servers, each server has its own set of tags(e.g., for food server: burger, pizza,...) and each server can have multiple posts(just like Reddit). so how can I make it so that the user can choose between tags when creating a new post? user should only be able to choose on of the tags dedicated to the server which the post is going to be posted on. I've made a ServerTag model to save tags when creating a new server: class ServerTag(models.Model): server = models.ForeignKey(Server, on_delete=models.CASCADE, related_name='tags') name = models.CharField(max_length=20) primary_color = ColorField(default = '#ffff') secondary_color = ColorField(default = '#ffff') is_allowed = models.BooleanField(default=True) def __str__(self) -> str: return f'{self.name} --> r/{self.server}' Server model: class Server(models.Model): creator = models.ForeignKey(User , on_delete=models.CASCADE) created = models.DateTimeField(auto_now=True) name = models.CharField(max_length=50) about = models.TextField(default='about') tag = models.CharField(max_length=50) slug = models.SlugField(default='server') image = models.ImageField(upload_to='servers/pic/') header_image = models.ImageField(upload_to='servers/header-pic/') members_count = models.IntegerField(default=0) online_count = models.IntegerField(default=0) required_karma = models.IntegerField(default=0) def __str__(self): return self.name and Post Model: class Post(models.Model): post_type_choices = [('text', 'text'), ('video', 'video'), ('image', 'image'), ('link','link')] title = models.CharField(max_length=200) slug = models.SlugField(max_length=50, default='slug') text = models.TextField(null=True, blank=True) text_allowed = models.BooleanField(default=True) image = models.ImageField(upload_to='posts/images/', null=True, blank=True) image_allowed = models.BooleanField(default=True) video = … -
ModuleNotFoundError: No module named 'models. Unable to import models into folder
I'm creating a project in django called social_monitoring and I'm getting the error within the app 'fb_scraping'. I'm trying to import models from the models folder that I have created into a python file in another folder in the same directory. But, it keeps giving me this error from models.scrapingmodels import Scrapedposts, Postcomments Error: ModuleNotFoundError: No module named 'models' The structure of the project: social_monitoring/ --└── fb_scraping/ -----├── models/ -----│ -----├──__init.py__ -----│ -----└──scrapingmodels.py (where I'm importing from) -----└── scripts/ -----------└──fbscrape.py (where I'm importing to) scrapingmodels.py contains 2 class: Scrapedposts and Postcomments In the init.py file in models folder, I've added: from .scrapingmodels import Scrapedposts as _Scrapedposts from .scrapingmodels import Postcomments as _Postcomments In fbscrape.py, I have tried to import in several ways: from fb_scraping.models.scrapingmodels import Postcomments, Scrapedposts and i get the error: ModuleNotFoundError: No module named 'fb_scraping' What do you suggest I do to fix this issue? -
audio cannot played but detected to local storage
my website have form using models to upload audio file. when it uploaded, the file cannot be played but at my terminal it’s already detected the file name. but when i open new page, the audio can be play without i need to upload again. anyone know what’s wrong? here’s my html: <audio controls="controls"> <source src="/media/mp3/{{last_audio.audio}}" type="audio/mpeg"> </audio> views.py: def homepage(request): form = AudioForm() last_audio = Audio_store.objects.all().last() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): audio = form.cleaned_data.get("audio") print(audio) context={'form':form, 'last_audio':audio} print(context) form.save() return render(request, "homepage.html", context=context) context={'form':form, 'last_audio':last_audio} return render(request, "homepage.html", context=context) models.py: from django.db import models from django.core.files.storage import FileSystemStorage fs = FileSystemStorage(location='media/mp3') fss = FileSystemStorage(location='media/txt') class Audio_store(models.Model): password=models.FileField(storage=fss, null=True) audio=models.FileField(storage=fs, null=True)