Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to treat null as equal to everything for uniqueness constraints?
In the title I mean equal to any value, not just to other nulls. Let's say for the sake of the example that we have a household, with household members (people) and electronic devices. Some electronic devices are personal and belong to one person, but some do not belong to any one household member, like for example a common computer in the study. We might then model electronic devices like this: class ElectronicDevice(models.Model): name = models.CharField(null=False, max_length=64) owner = models.ForeignKey(HouseMember, null=True, on_delete=models.CASCADE) Now let's say we want device names to be unique from the perspective of house members. A house member should not have two devices available for them which have the same name. So name and owner should be unique together, but there should also not be two devices, one private and one common (owner is null) which have the same name. Thus a normal UniqueConstraint: class Meta: constraints = [ models.UniqueConstraint(fields=['name', 'owner'], name='uniqe_device_name'), ] would not do, since it still allows two devices to have the same name if for one of them owner is null. Only constraining the name field: class Meta: constraints = [ models.UniqueConstraint(fields=['name', ], name='uniqe_device_name'), ] also would not do, because this would not … -
Access User object from FilterSet init Django
I am trying to set django filter choices for User Groups. I have tried setting the init function but I am not able to get the self.request to access user's groups. def __init__(self, *args, **kwargs): super(Filter, self).__init__(*args, **kwargs) self.filters['group'].extra['choices'] = [ (group.id, group.name) for group in self.request.user.groups.all() ] -
Django: How do I remove the ending "?" from the URL
I need to remove the "?" at the end of my URL: urls.py urlpatterns = [path("map_fslis_top/totals/<int:fstype_id>", views.edit_totals, name="edit_totals"),] view.py def edit_totals(request, fstype_id): # Some code... return render(request, "DataMech/totals.html", { 'fstype': fstype, 'typefslis': typefslis, 'totals': totals, }) html trigger <button href="{% url 'edit_totals' fstype_id=fstype.id %}" class="btn btn-primary" class="form-control" type="submit" value="submit">Totals</button> The URL of the page generated: http://127.0.0.1:8000/map_fslis_top/totals/1? How do I get rid of that ugly "?" at the end of the URL? -
Django development stage best practice
I am going to be working on a Django Project for my final requirement in school, and I am wondering if I should use PostgreSQL on development stage or if I should stick with built-in sqlite3 during development. I am worried if I used sqlite3 on development stage there will be problems with migrations if I switch to PostgreSQL on Production. -
I added a timefield in a model in django, when I applied migrations there was an error, when I removed that field in the model there still was error
Error: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, tohome Running migrations: Applying tohome.0003_auto_20210323_1611...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\core\management\commands\migrate.py", line 245, in handle fake_initial=fake_initial, File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\db\migrations\operations\fields.py", line 106, in database_forwards field, ) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site-packages\django\utils\dateparse.py", line 90, in parse_time match = time_re.match(value) TypeError: expected string or bytes-like object models.py from django.db import models class Task(models.Model): title = models.CharField(max_length =200) complete = models.BooleanField(default = False , blank=True) created = models.DateTimeField(auto_now=True) settime = models.TimeField((""), auto_now=False, auto_now_add=False) def __str__(self): return … -
I'm getting this error when i'm trying runserver in pycharm
File "C:\Users\rajiv\anaconda3\envs\deep learning\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Users\rajiv\anaconda3\envs\deep learning\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\rajiv\PycharmProjects\pyshop\venv\Scripts\django-admin.exe\__main__.py", line 7, in <module> File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\core\management\commands\testserver.py", line 34, in handle db_name = connection.creation.create_test_db(verbosity=verbosity, autoclobber=not interactive, serialize=False) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\db\__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\db\utils.py", line 211, in __getitem__ self.ensure_defaults(alias) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\db\utils.py", line 172, in ensure_defaults conn = self.databases[alias] File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\db\utils.py", line 153, in databases self._databases = settings.DATABASES File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\conf\__init__.py", line 67, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or ca ll settings.configure() before accessing settings. -
How to get values for a chart with JavaScript in Django?
I created an application with Django. In this system, there is an approval system. I created an ApprovalProcess model and it has a beginning_date field. I crated a chart for showing how many approval processes are started on which day? But I cannot fill this chart. But I cannot figure it out how can I get approval process values as my data? models.py class ApprovalProcess(models.Model): id = models.AutoField(primary_key=True) user_id = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='starter') doc_id = models.ForeignKey(Pdf, on_delete=models.CASCADE, null=True) begin_date = models.DateTimeField(auto_now=True) end_date = models.DateTimeField(auto_now=True) status = models.IntegerField(default=0) highest_rank = models.IntegerField(default=0) last_approved = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='last_approved') customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) views.py def approval_context_processor(request): if request.user.is_authenticated: current_user = request.user rank_priority = RankPriority.objects.filter(rank=current_user.rank) priority = rank_priority[0].priority pend_list = ApprovalProcess.objects.filter(status=priority) submit_list = ApprovalProcess.objects.filter(user_id=current_user) userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company) all_approvals = ApprovalProcess.objects.filter(user_id__company=request.user.company) approved_reports = 0 waiting_reports = 0 for submit in submit_list: if submit.status - submit.highest_rank == 1: approved_reports += 1 else: waiting_reports += 1 else: pend_list = 0 submit_list = 0 context = { 'pend_list': pend_list, 'submit_list': submit_list, 'approved_reports': approved_reports, 'waiting_reports': waiting_reports, 'customer_list': customer_list, 'all_approvals': all_approvals } return context chart <div class="row"> <div class="col-md-8"> <div class="card"> <div class="card-header"> <div class="card-head-row"> <div class="card-title">User Statistics</div> <div class="card-tools"> </div> </div> </div> <div class="card-body"> … -
Django signals not executed
I have a problem with Django signals, I don't know why but they are not executed. I have created an "events" application with some views, everything works except the signals. My model : class Events(models.Model): """ Events """ name = models.CharField(verbose_name="Nom", max_length=50) date_start = models.DateTimeField(verbose_name="Date de début") date_end = models.DateTimeField(verbose_name="Date de fin") address = models.CharField(verbose_name="Adresse", max_length=80) postal_code = models.PositiveIntegerField(verbose_name="code postal") city = models.CharField(verbose_name="Ville",max_length=50) registered_users = models.ManyToManyField(User, verbose_name="Personnes inscrites", related_name="event_registered_users", blank=True) max_users = models.PositiveSmallIntegerField(verbose_name="Nombre de personnes maximum") is_internal = models.BooleanField(verbose_name="Réservé aux membres de l'association ?") category = models.ForeignKey(CategoryEvent, verbose_name="categorie", on_delete=models.CASCADE) class Meta: verbose_name = "évènement" verbose_name_plural = "évènements" def __str__(self): return self.name My function linked to a signal: from .models import Events @receiver(post_save, sender=Events) @receiver(post_delete, sender=Events) def delete_cache_event_events(sender, instance, **kwargs): """ Clear cache """ print("clear") cache.delete(f"details_event_{instance.pk}") cache.delete(f"list_events_categories_{instance.category.pk}") If I save a new event or update an existing one, the signal is not executed. (the cache is not cleared and I can't see "clear" in the console). -
python django pymysql query formatting datetime output?
python3.8 sql sql="select * from target" def dictfetchall(cursor): "Return all rows from a cursor as a dict" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] with connection.cursor() as cursor: cursor.execute(sql_query) data = dictfetchall(cursor) return data data output is [{ "name": "tom", "congestion_level": null, "arrival_flow": 15.0, "ctime": "2020-04-11T12:00:00" }, { "name": "jack", "congestion_level": null, "arrival_flow": 25.0, "ctime": "2020-04-11T12:00:00" }] ctime this fields has T,if i rmeove T i need run following code def datetime_to_str(old_dict_list): for old_dict in old_dict_list: for x, y in old_dict.items(): if isinstance(y, datetime.datetime): old_dict[x] = datetime.datetime.strftime(y, '%Y-%m-%d %H:%M:%S') return list(old_dict_list) I think my method is not pythonic,I don’t want to use django orm because of the complex sql statement -
How to filter data between two dates in Django?
I am trying to develop a blood donation app. Here I need to get the donor's data which have last donated date more than 6 months ago that is if the donor has donated in last six months the donor's data should not be rendered to the template. I am trying to do that but could not figured out to do. So if anyone can help me then thank you in advance. Here is a column in models.py lastDonatedDate = models.DateField(blank=True, null=True) I just need to filter the donor's detail from the current date and the difference between two dates should be greater than 6 months. -
Django Rest Framework get data from related table
I have a database table of cards, and this has a relationship with another table of sets that those cards belong to. The Cards tables has a foreign key, set_id which links the two tables togethers. When I return the the card data, I am struggling to return the related data for the sets the cards belong to. models.py class Set(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) code = models.CharField(max_length=64) ... objects = models.Manager() def __str__(self): return self.name class Card(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... set = models.ForeignKey(Set, on_delete=models.CASCADE, related_name='cards', related_query_name='cards') objects = models.Manager() def __str__(self): return self.name @property def manaCostList(self): a0 = self.manaCost.replace('//', '{//}') a1 = a0.split('{') a2 = [s.strip('} ') for s in a1] a3 = [s.replace('//', 'slash') for s in a2] a4 = [s.replace('/', '') for s in a3] a5 = list(filter(None, a4)) return a5 serializers.py class SetSerializers(serializers.ModelSerializer): class Meta: model = Set fields = '__all__' class CardSerializers(serializers.ModelSerializer): cards = SetSerializers(many=True, read_only=True) class Meta: model = Card fields = '__all__' extra_fields = ['cards', 'manaCostList'] def get_field_names(self, declared_fields, info): expanded_fields = super(CardSerializers, self).get_field_names(declared_fields, info) if getattr(self.Meta, 'extra_fields', None): return expanded_fields + self.Meta.extra_fields else: return expanded_fields In my JavaScript when I perform a console.log(b) there is no data from … -
How do I add a subdomain to react app DRF
I'm building a hybrid Django/DRF - React website. I'd like the react section to have a subdomain asits only a part of the website. Currently react renders correctly without the subdomain, however when I add a subdomain to urls.py, index.html renders but without the components. React is in a django app, and the APi is in another django app. This is the code with the subdomain of 'app' added: src/components/App.js <Route path="app/join" component={RoomJoinPage} /> <Route path="app/info" component={Info} /> <Route path="app/create" component={CreateRoomPage} /> (react app) frontend urls.py from django.urls import path from .views import index app_name = 'frontend' urlpatterns = [ path('', index, name=''), path('info', index), path('join', index), django project urls.py from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('spotify/', include('spotify.urls')), path('app/', TemplateView.as_view(template_name='frontend/index.html')), path('main/', include('main.urls')), ] -
Apply Django permissions based on Request and Model
I'm pretty new to Django and what I'm trying to achieve is utilizing Django's permissions in my apps without actually writing code for each view/request(post/...). I have a lot of groups with a veracity of permissions associated with them and it's really hard to check every and each one of these permissions. Let's say I've got a model named Article and a group named readers with only one permission: article.read_article; And there is a form on the home page which can be used to add new articles. Is there any way to stop the users in the reader group from adding new articles using this form without actually writing code for it? For example, based on Request, Group, Permissions, and Models involved. Or write something in the model to check all necessary permissions before executing a query. -
Best practice in updating Django web app content when deployed on Heroku
I'm finally at the stage of deploying my Django web-app on Heroku. The web-app retrieves and performs financial analysis on a subset of public companies. Most of the content of the web-app is stored in .csv and .xslx files. There's a master .xslx file that I need to open and manually update on a daily basis. Then I run scripts which based on info in that .xsls file retrieve financial data, news, etc and store the data in .csv files. Then my Django views and html templates are referring to those files (and not to a sql/postgress database). This is my setup in a nutshell. Now I'm wondering what is the best way to make this run smoothly in production. Shall I store these .xslx and .csv files on AWS S3 and have Django access them and update them from there? I assume that this way I can easily open and edit the master .xslx file anytime. Is that a good idea and do I run any performance or security issues? Is it better to convert all these data into a postgress database on Heroku? Is there a good guideline in terms of how I can technically do that? In … -
Django And Restful API Oauth2 Login
I'm extremely new to Django and I could really use some help on integrating the restful API into my application. I've built a simple twitter clone, and I have a login page. I want to allow users to register but using the OAuthV2 protocol. (I.e register and login on the login page but using the api in the backend) I understand how to create a RESTful SaaS but only on the backend and I can't seem to figure out how I would go about integrating it with my front end. If someone could please explain the process to me or help me out with some resources I'd really appreciate it. -
Why does my data form my word form don't save?
So I have created a Form with an id and some words and now I wanted to store it in a DB table I have in my MySQL DB. But for some reason, when I hit the submit button the Object saves but there is no data in it. my forms.py: class WordForm(forms.ModelForm): SessionID = forms.CharField(label= 'Session ID', widget= forms.TextInput(attrs={ 'placeholder': 'Please enter your session ID' })) Word1 = forms.CharField(label= 'Word1', widget= forms.TextInput(attrs={ 'placeholder': 'Enter First Word' })) Word2 = forms.CharField(label= 'Word2', widget= forms.TextInput(attrs={ 'placeholder': 'Enter Second Word' })) Word3 = forms.CharField(label= 'Word3', widget= forms.TextInput(attrs={ 'placeholder': 'Enter Third Word' })) Result = forms.CharField(label= 'Result', required=False, widget= forms.TextInput(attrs={'class': 'form-control', 'readonly': 'True'})) mode_selection = forms.ChoiceField(choices=MODE_SELECTION, label='Please Select an Option:', widget=forms.RadioSelect) class Meta: model = WordsTable fields = ('SessionID', 'Word1', 'Word2', 'Word3', 'Result') my models.py: class WordsTable(models.Model): session_id = models.IntegerField(db_column='session_ID', blank=True, null=True) # Field name made lowercase. user_id = models.IntegerField(db_column='user_ID', blank=True, null=True) # Field name made lowercase. date = models.DateField(blank=True, null=True) hour = models.TimeField(blank=True, null=True) run_label = models.IntegerField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) word1 = models.CharField(max_length=45, blank=True, null=True) word2 = models.CharField(max_length=45, blank=True, null=True) word3 = models.CharField(max_length=45, blank=True, null=True) word4 = models.CharField(max_length=45, blank=True, null=True) word5 = models.CharField(max_length=45, blank=True, null=True) class Meta: db_table = 'words_table' … -
How to add an attribute to Django request object
I try to add the business attribute to the request object by using my own middleware, it nicely works with rest_framework.authentication.SessionAuthentication and I can use request.business in my views. But when I try to authenticate with JWT method (rest_framework_simplejwt.authentication.JWTAuthentication) when my middleware code is run request.user is set to AnonymouseUser so can't fetch business associated with user? Why did this happen? # middleware.py class AddBusinessObjectToRequestMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): request.business = None if request.user.is_authenticated and hasattr(request.user, 'profile') and hasattr( request.user.profile, 'business'): request.business = request.user.profile.business response = self.get_response(request) return response -
Link to a specific tab in another page with an anchor tag by using Django and javascript
I have an href link in one page, when clicking I need to open a specific tab in another page. In the second page I have multiple tabs. In more detail: Page 1 I'm using Django template tag with anchor to go to the page with the tabs. url is http://127.0.0.1:8000/payments#payments <div class="shop-info"> <a href="{% url 'payments' %}#payments"> <div class="footer-links">Payments</div> </a> <div class="footer-links">Shipping</div> <div class="footer-links">Returns</div> </div> Page 2 <div data-duration-in="300" data-duration-out="100" class="tabs w-tabs"> <div class="tabs-menu w-tab-menu"> <a data-w-tab="Tab 1" class="tab-links w-inline-block w-tab-link"> <div>Payments</div> </a> <a data-w-tab="Tab 2" class="tab-links w-inline-block w-tab-link"> <div>Shipping</div> </a> </div> <div class="tabs-content w-tab-content"> <div data-w-tab="Tab 1" class="payments-text w-tab-pane"> <div class="w-richtext"> {{ settings.payments|safe }} </div> </div> <div data-w-tab="Tab 2" class="shipping-text w-tab-pane"> <div class="w-richtext"> {{ settings.shipping|safe }} </div> </div> </div> I understand that in order for this to work i need to use some javascript however i'm not quite familiar. After reading a couple of similar issues I added following code in the page 2 but with no success: <script> $(document).ready(function(){ // get the tab from url var hash = window.location.hash; // if a hash is present (when you come to this page) if (hash !='') { // show the tab $('.nav-tabs a[href="' + hash + '"]').tab('show'); } }); … -
Django inlineformset_factory validators not working
Code Snippet Django version: 3.1.7 models.py # custom validator is_numeric = RegexValidator(r"^[0-9]*$", "Only numbers are allowed") class Person(models.Model): # all the boring fields class PersonAddress(models.Model): # all the boring fields person = models.ForeignKey( Person, null=True, on_delete=models.SET_NULL, related_name="person_address", ) postcode = models.CharField( blank=True, help_text="Include leading zero if exists", max_length=10, validators=[is_numeric], ) PersonAddress will be the inlineformset of Person as a Person can have multiple addresses forms.py class PersonForm(forms.ModelForm): class Meta: model = Person fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() class PersonAddressForm(forms.ModelForm): class Meta: model = PersonAddress fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = "post" PersonAddressFormSet = forms.models.inlineformset_factory( Person, PersonAddress, form=PersonAddressForm, extra=1, can_delete=True, ) # min_num, validate_min don't help even though I read from other stackoverflow solution # PersonAddressFormSet = forms.models.inlineformset_factory( # Person, PersonAddress, form=PersonAddressForm, extra=1, can_delete=True, min_num=1, validate_min=True, # ) views.py # Person CreateView class PersonCreateView(SuccessMessageMixin, LoginRequiredMixin, CreateView): model = Person form_class = PersonForm def get_context_data(self, **kwargs): context = super(PersonCreateView, self).get_context_data(**kwargs) if self.request.POST: context["addresses"] = PersonAddressFormSet(self.request.POST, self.request.FILES) else: context["addresses"] = PersonAddressFormSet() return context # I think the problem is here, not 100% sure def form_valid(self, form): context = self.get_context_data() addresses = context["addresses"] self.object = form.save() if addresses.is_valid(): addresses.instance … -
create new temporary user with a login user in django
I'm stuck in the attempt to create an appointment application with Django to register (as a patient) and non registered user (doctor makes appointment for non register patient) my idea is to create a new user with a type = temporary with usereditform and after creating this user we can add an appointment for his (This allows us not to write down this patient information every time he wants to book an appointment -his information will be registered as a temporary user-) but after searching, I find out that there is a way to create a user without password or email I add some information to the user model to make it easy for the one who wants to book an appointment and after creating this user we can add he appointment information this is the models .py class TypeOfUser(models.TextChoices): PATIENT = 'patient', 'Patient' DOCTOR = 'doctor', 'Doctor' RECEPTION = 'reception', 'Reception' TEMPORARY = 'temporary', 'Temporary' class AllowdToTakeAppointement(models.TextChoices): YES = ('yes', 'Yes') NO = ('no', 'No') class User(AbstractUser): type_of_user = models.CharField(max_length=200, choices=TypeOfUser.choices, default=TypeOfUser.PATIENT) allowd_to_take_appointement = models.CharField(max_length=20, choices=AllowdToTakeAppointement.choices, default=AllowdToTakeAppointement.YES) # profile information in user models BLOOD_GROUPS = [ ('O-', 'O-'), ('O+', 'O+'), ('A-', 'A-'), ('A+', 'A+'), ('B-', 'B-'), ('B+', 'B+'), ('AB-', … -
Related Field got invalid lookup: user (While exclude)
I am building a BlogApp and I am stuck on an Error. What i am trying to do :- I am trying to exclude the users that are my followers from the BlogPost Page. I am using exclude method to exclude the users. When i go to the browser then it keep showing :- Related Field got invalid lookup: user models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') followers = models.ManyToManyField(User,blank=True,related_name='user_followers') views.py @login_required def posts(request): followed_users= request.user.profile.followers.all() posts = Post.objects.filter(date_added__lte=now).exclude(post_owner__user=followed_users) context = {'posts':posts} return render(request, 'mains/post.html', context) What have i tried I also tried replacing .exclude(post_owner__user=followed_users) into exclude.(post_owner__profile=followed_users) BUT then i got Cannot use QuerySet for "User": Use a QuerySet for "Profile". I don't know what i am doing wrong. Any help would be Appreciated. -
Django on Heroku - 'psycopg2.errors.UndefinedTable: relation "prices_tool_car" does not exist' caused by query in forms.py
first of all I would like to say that I googled this error and I run both migrate and makemigrations. I also made sure that my migrations folder is on heroku server and that it is not empty. My problem is this error: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "prices_tool_car" does not exist LINE 1: ...NT("prices_tool_car"."model") AS "count" FROM "price... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/app/.heroku/python/lib/python3.8/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/functional.py", line 48, in … -
How can I make custom image path with static_url in Django?
I have six images name as 1.jpg to 6.jpg of each side of dice I want a simple aim, by the random modual number is generated between 1 to 6 and picture of this side is displayed now problem is that how can I make custom path I tried both the syntax but anyone is not fatch the image and 404 image not found show. static file be like STATIC_URL = '/static/' my path for the image is like D:\programs\Django_projects\src\dice\random_dice\static\images here, dice is my project name and random_dice is my app name. Should I move image folder to else position or change STATIC_URL or the syntax is wronge I have no idea please help I already tried this ... <img class="myImage" src='{% static "images/{{ number }}.jpg"%}' alt="can not load the image"> And <img class="myImage" style="background-image:url('{{ STATIC_URL }} images/{{ number }}.jpg')" alt="can not load the image"> I also tried , before the randering of the page make custom name and put in dict but not working in view.py def home(request): X = random.randrange(1, 6) result = { "number": X, "myImage": str(X) + '.jpg' } return rander(request, 'home.html', result) In that condition ... <img class="myImage" src='{% static "images/{{ myImage }}"%}' alt="can not … -
NonType object has no attribute user_email
models.py class userDetails(models.Model): user_id=models.AutoField(primary_key=True) user_name=models.CharField(max_length=20) user_email=models.EmailField() class LoginDetails(models.Model): user_id=models.ForeignKey(userDetails,null=True,on_delete=models.CASCADE) admin_id=models.ForeignKey(AdminDetails,null=True,on_delete=models.CASCADE) driver_id=models.ForeignKey(DriverDetails,null=True,on_delete=models.CASCADE) login_id=models.CharField(max_length=20) login_password=models.CharField(max_length=20) login_status=models.CharField(max_length=20) Here in LoginDetails model I will be inserting user_id if user is registering, driver_id when driver registering. And I need To select users which have status="not approved" using select_related(). But I am getting NoneType error when writing below code, user_list=LoginDetails.objects.all().select_related('user_id') for user in user_list: print(user.user_id.user_email) Anyone please help . -
How can I add unlimited field in models on admin page
In Django project that I made I just made a product model that user customize it with how much field want by what kind of product wants add, so I don't know what kind of product admin wants add to make field for it, so how can solve this problem ?