Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-channels:chatSocket.onmessage or chatSocket.send does not work
I'm trying to implement a django channels chat app. when the submit button of the room view is clicked, the message does not appear in the chat log. which make me think that somethings wrong with chat.onmessage command, it does not seem to fire. can someone help me fix the issue. here is the code for room view: <!-- chat/templates/room.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <textarea id="chat-log" cols="100" rows="20"></textarea><br/> <input id="chat-message-input" type="text" size="100"/><br/> <button id="chat-message-submit" type="submit" value="Send">Send</button> </body>z <script> var roomName = {{ room_name_json }}; var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); chatSocket.onmessage = function(e) { console.log("got to onmessage"); var data = JSON.parse(e.data); var message = data['message']; document.getElementById('chat-log').value += (message + '\n'); }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.getElementById('chat-message-submit').click(); } }; document.getElementById('chat-message-submit').onclick = function(e) { var messageInputDom = document.getElementById('chat-message-input'); var message = messageInputDom.value; console.log("got message : " + message); chatSocket.send(JSON.stringify({ 'message': message })); console.log("This was done?"); messageInputDom.value = ''; }; </script> </html> Here is my consumer view : from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def … -
django KeyError at (request)
I am making a program and I have a small problem. I'm currently designing a web page with python django and requests, and I have an Error which mentions That Key Error at 'main' and here are my codes form: from django.forms import ModelForm, TextInput from .models import City class CityForm(ModelForm): class Meta: model = City fields = ['name'] widgets = {'name' : TextInput(attrs={'class':'input', 'placeholder' :'City Name'})} models: from django.db import models class City(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Meta: verbose_name_plural = 'cities' views: import requests from django.shortcuts import render from .models import City from .forms import CityForm def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=212c1f52ec8c8bbf34933937a6885114' if request.method == 'POST': form = CityForm(request.POST) form.save() form = CityForm() cities = City.objects.all() weather_data = [] for city in cities: r = requests.get(url.format(city)).json() city_weather = { 'city' : city.name, 'temprature' : r['main']['temp'], 'description' : r['weather'][0]['description'], 'icon' : r['weather'][0]['icon'], } weather_data.append(city_weather) context = {'weather_data' : weather_data, 'form' : form} return render(request, 'weather_data/weather.html', context) I tried everything I could, and it didn't make it I erased the 'main' part and any other things... finally nothing worked. I have an error message like this: Environment: Request Method: GET Request URL: http://codefair-tripple-wrbdv.run.goorm.io/ Django Version: 2.1 Python Version: … -
How to concept a web application (dashboard) made of Django in terms of backend structure
My goal is to build a python/django based dashboard related to soccer where the user can select a soccer team of his choice in the sidebar and then gets all related data displayed in the dashboard in return. I attached the html frontend so you can get a brief feeling of how it will look like. As for the backend, I am not quiet sure what might be a good or even the best solution structurewise. I hope to get some input/opinions from the community to derive a good approach for my further steps. I inserted numbers to the questions for the sake of clarity ;). Templates Since the web application will contain one main site (= the dashboard) I prefer to wortk with a single template (index.html, apart from "about" and "blog" sites). [1.1] Is there any good reason to maybe split the sidebar and the dashboard part into two templates? [1.2] Or even to create a single template for each "part" of the dashboard (Like one template for each single information container)? Views As I understand from different tutorials/documentations you usually just use one views.py file in a web application. I will grab the soccer data from an … -
django model many to one individual id
i tried to make a ID that depends on parent's Field. like this, My Intention BOOK my new friend is so fun! Some book own diaries! DOCUMENT Parent : my new friend is so fun! book cover table of content content blablaah. Parent: Some book Some Book Cover table of content content ~~ Unintended consequences(problem) BOOK my new friend is so fun! Some book own diaries! DOCUMENT Parent : my new friend is so fun! 1. book cover 2. table of content 3. content blablaah. Parent: Some book 4. Some Book Cover 5. table of content 6. content ~~ class Book(models.Model): publisher = models.ForeignKey(User, on_delete=models.CASCADE) book_id = models.AutoField(primary_key=True) book_name = models.CharField(max_length = 30) def __str__(self): return self.book_name class Document(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) document_id = models.AutoField(primary_key=True) title = models.CharField(max_length = 50) def __str__(self): return self.title for ordering this document i have to make some field instead of pk field. anyway, i have to make a edit page, and user can change their order in edit page. that document_id is overall model. how can i make it? -
django-reversion conflict with models clean method
i use django-reversion to controll changes of my models but i have a problem with the models clean method. For example my model looks like this: class Document(models.Model): name = models.CharField(max_length=255, blank=True, null=True) client = models.ForeignKey(Client, on_delete=models.CASCADE) template = models.ForeignKey(Template, on_delete=models.CASCADE) def clean(self): if self.template.only_one and (Document.objects.filter(client=self.client, template=self.template).count() > 0): raise ValidationError('Test') I register this model in the admin.py: @admin.register(Document) class DocumentReversion(VersionAdmin): pass Now i create a record for Document in the admin section referencing to a template where the field only_one is True. If i delete this record and retrieve it, a ValidationError fires. Why? Because i have deleted the only available record. Very curious... -
Getting this error while populating through faker
Faker error while populating a database It worked when i created populate_firstapp but now it is showing an error -
Problem with MySQL databases on a CentOS Droplet
I'm setting up a server for a website and a part of my application, and I'm using a DigitalOcean Droplet that's running CentOS 7. However, I simply can't connect to a database that's on the server, from the server. When I install MySQL 8.0 the service won't start, it says that it can't find mysql.sock, MySQL 5.7 works fine but I always get the "Error establishing a connection to the database" on my website. The user data for connecting to the database is fine, so we got to the conclusion that the Perl MySQL DBD module is missing, however when we try to install that it updates MySQL to version 8.0 and MySQL won't start then. We are not sure which versions we are supposed to use, any help would be appreciated. We are using Python 2.7 and Django 1.12 '''Warning: The Perl module DBD::mysql is not installed on your system, so Webmin will not be able to reliably access your MySQL database. Click here to install it now. '''' -
KeyError, Exception Value: 'object'
1 I'm working on Django. I'm getting the error below. I didn't find the solution despite the much increased. Codes in views.py class UpdateVote(LoginRequiredMixin,UpdateView): form_class = VoteForm queryset = Vote.objects.all() def get_object(self,queryset=None): vote = super().get_object(queryset) user = self.request.user if vote.user != user: raise PermissionDenied('can not change another user vote') return vote def get_success_url(self): movie_id = self.object.movie.id return reverse('core:movie_detail', kwargs={'pk':movie_id}) def render_to_response(self, context, **response_kwargs): movie_id = context['object'].id movie_detail_url = reverse('core:movie_detail',kwargs={'pk':movie_id}) return redirect(to=movie_detail_url) class MovieDetail(DetailView): queryset = Movie.objects.all_with_prefetch_persons() def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) if self.request.user.is_authenticated: vote = Vote.objects.get_vote_or_unsaved_blank_vote(movie=self.object,user=self.request.user) if vote.id: vote_url_form = reverse('core:UpdateVote',kwargs={'movie_id':vote.movie.id,'pk':vote.id}) else: vote_url_form = (reverse('core:create_vote',kwargs={'movie_id':self.object.id})) vote_form = VoteForm(instance=vote) ctx['vote_form'] = vote_form ctx['vote_url_form'] = vote_url_form return ctx Codes in form.py I have used this form to link with UpdateView from django import forms from django.contrib.auth import get_user_model from .models import Movie,Vote class VoteForm(forms.ModelForm): user = forms.ModelChoiceField(widget=forms.HiddenInput,queryset=get_user_model().objects.all(),disabled=True) movie = forms.ModelChoiceField(widget=forms.HiddenInput,queryset = Movie.objects.all(),disabled=True) value = forms.ChoiceField(widget=forms.RadioSelect,choices=Vote.VALUE_CHOICE) class Meta: model = Vote fields = ('value','user','movie',) urls.py This is the url mapping for the view. from django.contrib import admin from django.urls import path from .views import MovieList,MovieDetail,PersonDetail,CreateVote,UpdateVote app_name = 'core' urlpatterns = [ path('movies/', MovieList.as_view(), name='movie_list'), path('movie/<int:pk>/', MovieDetail.as_view(), name='movie_details'), path('person/<int:pk>/', PersonDetail.as_view(), name='person_details'), path('movie/<int:movie_id>/vote/', CreateVote.as_view(), name='create_vote'), path('movie/<int:movie_id>/vote/<int:pk>', UpdateVote.as_view(), name='UpdateVote'), ] HTML template This is the … -
Django. Rest framework. How to add object ID in XML?
In DRF, I create XML in which I need to assign the object id to the main tag It should look as follows: <offer internal-id="Object ID"> <type></type> <category></category> <url></url> </offer> I have a problem with the offer tag as I don’t know how to insert the object ID into it. Nested tags are generated perfectly, there are no problems with them. Here is my views.py: class ZemlaXMLRenderer(XMLRenderer): root_tag_name = 'feed' item_tag_name = 'offer' def _to_xml(self, xml, data): if isinstance(data, (list, tuple)): for item in data: xml.startElement(self.item_tag_name, {'internal-id': 'Object ID'}) self._to_xml(xml, item) xml.endElement(self.item_tag_name) super()._to_xml(xml, data) Ideally, the output should be the following structure: <offer internal-id="1"> <type></type> <category></category> <url></url> </offer> <offer internal-id="2"> <type></type> <category></category> <url></url> </offer> Thank! -
Django Converting to CBV + tests
I'm trying to test my app. I went over the documentation, and managed to make the test for my URL's and all views but one. I'm having trouble converting it to a class view and I'm not really sure what kind of tests should I do here ? Anyone mind helping me out ? here is the view that I'm trying to convert and test : def add_comment_to_article(request, pk): article = get_object_or_404(Article, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = article comment.save() return HttpResponseRedirect(reverse('news:article', kwargs={"article_id": article.pk})) else: form = CommentForm() return render(request, 'news/add_comment_to_article.html', {'form': form}) The view is in charge of adding a comment to my Article post. Thank you !! -
Django-ckeditor not loading edits with crispy-forms
I have a cripsy form and I want to change one field from Textarea to CKEDitorUploadingWdidget So my form looks like this (I have left in what was previoulsy working: class RenameStudyForm(BetterModelForm): name = forms.CharField(label='Study Name', max_length=51, required=False) # Update study name #waiver = forms.CharField(widget=forms.Textarea, label='Waiver of Documentation', required=False) waiver = forms.CharField(widget=CKEditorUploadingWidget(), label='Waiver of Documentation', required=False) I have amended my model as follows: class study(models.Model): researcher = models.ForeignKey("auth.user") # Researcher's name name = models.CharField(max_length = 51) # Study name instrument = models.ForeignKey("instrument") # Instrument associated with study #waiver = models.TextField(blank = True) waiver = RichTextUploadingField(blank = True) My template looks has: {% load crispy_forms_tags %} {{ form.media }} {% crispy form %} When I enter the screen to edit the waiver I get a rich text field to edit, as I would expect. However, nothing I enter into the field is passed back to the form. Within the form I added a print statement, as below def clean(self): cleaned_data = super(RenameStudyForm, self).clean() print(cleaned_data['waiver']) The print always gives the original text. Can anyone help me please -
use Django request.session inside utility function
I am trying to call request.session.get('items', {}) from a custom util function util.py. but in that file, request object is not accessible, I can pass the request object from views.py but i don't want to. is there any way to use request object inside the custom functions (not view/template). I have tried to import from django.http import HttpRequest but this class doesn't have any session variable. django beginner, any help is appreciated thanks. util.py: def processData(data=None): ## get items form session items = request.session.get('items', {}) ## error name 'request' is not defined # append with data items.update(data) return items -
Rewriting functions of ModelViewSet with two serializers
EpisodeImage is connected with foreign key to Episode model. So, Episode has a multiple image loading. But, I am confused how perform all this things combined in API. According to this code everything about episodes works fine, but user has to be able add multiple images in episode, so i am thinking how to perform this by overriding methods. Also, there should be two serialiezers, but I don't think exactly how to do that. Creating different endpoint is bad idea, because during creating episode user will add images too. models.py class Episode(models.Model): ... story = models.ForeignKey(Story, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) episode_number = models.IntegerField(null=True) class EpisodeImage(models.Model): episode = models.ForeignKey(Episode, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to=upload_location) admin.py class EpisodeImageInline(admin.TabularInline): model = EpisodeImage extra = 3 class EpisodeAdmin(admin.ModelAdmin): inlines = [EpisodeImageInline] admin.site.register(Episode, EpisodeAdmin) serializers.py class EpisodeSerializer(serializers.ModelSerializer): story = serializers.IntegerField(source='story.id', read_only=True) class Meta: model = Episode fields = '__all__' class EpisodeImageSerializer(serializers.ModelSerializer): episode = EpisodeSerializer(read_only=True) class Meta: model = EpisodeImage fields = '__all__' views.py class EpisodeView(viewsets.ModelViewSet): serializer_class = EpisodeSerializer def get_queryset(self): story_id = self.kwargs['story_id'] return Episode.objects.filter(story=story_id) def perform_create(self, serializer): return serializer.save(story=story) def perform_update(self, serializer): return super(EpisodeView, self).perform_update(serializer) def perform_destroy(self, instance): return super(EpisodeView, self).perform_destroy(instance) -
Restart gunicorn in django codes
I deployed my Django application to the internet and every time after changing codes, I have to run this command to make changes happen: sudo systemctl restart gunicorn Is there any way to run this command through codes (for example in views)? or schedule it? Or is there any way to force Gunicorn restarts after changing in codes? I have tried Subprocess but I couldn't make it work. -
Multi searching DJANGO
I have just finished one tutorial where a user can search cities, but it is possible to enter only one city. If i would like to search Oslo, Budapest in the same time it is impossible. Do you know what can I add to change it? Views: from django.views.generic import TemplateView, ListView from django.db.models import Q from .models import City class HomePageView(TemplateView): template_name='home.html' class SearchResultsView(ListView): model = City template_name = 'search_results.html' def get_queryset(self): query = self.request.GET.get('q') object_list = City.objects.filter( Q(name__icontains=query) | Q(state__icontains=query) ) return object_list TEMPLATE: <h1>Search Results</h1> <ul> {% for city in object_list %} <li> {{ city.name }}, {{ city.state }} </li> {% endfor %} </ul> -
Converting SQL join query to django ORM
I am new to django models and trying to convert legacy MySQL queries to django models. I have two tables tb1 and tb2. I want to join the two and use both of their fields to get results. class Tb2(models.Model): tb2_id = models.ForeignKey('Tb1', models.DO_NOTHING, primary_key=True) profile = models.CharField(max_length=15) version = models.CharField(max_length=15) class Tb1(models.Model): id = models.BigAutoField(primary_key=True) job_id = models.BigIntegerField(blank=True, null=True) """ SELECT s.*, IF(count(distinct p.version)<=1, TRUE, FALSE) is_profile_same, MAX(p.version) ver, FROM tb1 s LEFT JOIN tb2 p ON p.tb2_id=s.id WHERE s.id in ('10','9') group by s.id """ Tb1.tb1.filter().select_related('Tb2').annotate(join_profiles=Count('id')) I have left joined the two tables on the ids. I am not sure how to add the if and max conditions using the fields of the tb2. Every time i try to use the fields it gives me FieldError. Can someone help? -
Daemonizing Celery--No module named 'celery' error
I'm trying to daemonize Celery 4.3.0 on Ubuntu 18 following the official documentation. This is for a Django project to off-load intensive tasks. When the server is running the celery.service should make the Celery worker available to process tasks. However, Apache2 won't even run. If I tail the Apache log I see: [Sun Sep 29 07:42:07.621273 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "<frozen importlib._bootstrap>", line 971, in _find_and_load [Sun Sep 29 07:42:07.621279 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked [Sun Sep 29 07:42:07.621285 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "<frozen importlib._bootstrap>", line 665, in _load_unlocked [Sun Sep 29 07:42:07.621291 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "<frozen importlib._bootstrap_external>", line 678, in exec_module [Sun Sep 29 07:42:07.621297 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed [Sun Sep 29 07:42:07.621303 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "/var/www/html/examgap/examgap/__init__.py", line 5, in <module> [Sun Sep 29 07:42:07.621307 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] from .celery import app as celery_app [Sun Sep 29 07:42:07.621313 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "/var/www/html/examgap/examgap/celery.py", line 5, in <module> [Sun Sep 29 07:42:07.621317 2019] [wsgi:error] [pid … -
Django filtering for URLs and VIEWS - "Page not found at /collection/..."
I am retruning all records for specific object in Django successfully. My url.py is path('city/', views.TestListCity.as_view()) From postman I just GET: http://192.168.99.100:8080/collection/city and it returns all records. Example: { "id": 3, "name": "Bor", "region": { "id": 2, "name": "Sun" } }, Now I want to filter records with column name. I tried this: urls.py path('city/(?P<name>.+)/$', views.TestListCity.as_view()), views.py class TestListCity(generics.RetrieveAPIView): serializer_class = TestListCitySerializer def get_queryset(self): name = self.kwargs['name'] return City.objects.filter(name=name) I try GET: http://192.168.99.100:8080/collection/city?name=Bor But then 404: <title>Page not found at /collection/city</title> I also tried second approach: urls.py path('city/<str:name>/', views.TestListCity.as_view()) views.py class TestListCity(generics.RetrieveAPIView): serializer_class = TestListCitySerializer queryset = City.objects.all() lookup_field = 'name' But exactly the same response. -
groupby action on django queryset
I have a db table like this: id | col1 | col2 | col3 1 | 2 | b | c 2 | 1 | a | a 2 | 2 | b | c 1 | 3 | b | c I need to write a queryset to have: {'id':1, 'count_col1': 5, 'id':2, 'count_col1':3} how can I do it? it can be done by groupby in pandas, but I don't know how to do it here. -
Bootstrap 4 select form field isn't working with django
I am new to django and using bootstrap4 form with django. When I use input field text and date it works fine and save data into django admin but if I add Select for categories, it doesn't work and returns following error: ValueError at / The view app_budgetlist.views.home didn't return an HttpResponse object. It returned None instead. I worked for 2 straight days and couldn't figure out what's wrong! Can you help please? Here is my code: models.py from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class MonthlyBudget(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) budget_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) forms.py from django import forms from .models import MonthlyBudget class MonthlyBudgetForm(forms.ModelForm): class Meta: model = MonthlyBudget fields = ['category', 'budget_amount'] view.py from django.shortcuts import render, redirect from .models import Category, MonthlyBudget from .forms import MonthlyBudgetForm def home(request): project = MonthlyBudget.objects.all() categories = Category.objects.all() if request.method == "POST": form = MonthlyBudgetForm(request.POST or None) if form.is_valid(): form.save() else: return render(request, 'home.html', {'project':project, 'categories':categories}) home.html <form class="form-inline" method="POST"> {% csrf_token %} <input type="text" name="budget_amount" class="form-control mb-2 mr-sm-2" id="budget-amount" placeholder="Amount"> <div class="form-group"> <label for="category">Select Category</label> <select id="category" class="taskCategory" name="category"> <option class="disabled" value="">Choose a category</option> {% for … -
Django: null value in column "is_admin" violates not-null constraint
Simple Question: Why do I get this error: Integrity Error: null value in column "is_admin" violates not-null constraint When I Create a User with This Code? # views.py user_obj = UserProfile.objects.create_user( username = 'username', email = 'test@example.com', password = 'password', ) The Error Sounds clear enough, except that I don't have a column called "is_admin" in my custom user model. I've tried specifying that "is_admin = False" in the code above and in the Customer user manager below, but when I do that, I get a new error that says 'is_admin' is an invalid keyword argument for this function - Here are the details... # models.py ### My Custom User Model Extending AbstractBaseUser class UserProfile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True) # ... other stuff [definitely nothing called "is_admin"] is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_editor = models.BooleanField(default=False) objects = UserProfileManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] As a sanity check, here is my Customer user manager: # models.py class UserProfileManager(BaseUserManager): def _create_user(self, username, email, password, **extra_fields): if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) username = self.model.normalize_username(username) user = self.model(username=username, email=email, **extra_fields) # user = self.model(username=username, email=email, is_admin = False, **extra_fields) … -
pre_delete signal not working in specific directory
i want remove file from storage when a File instance removed.trying to use django signal. here is my model File: class File(models.Model): orig_name = models.CharField(_('Original Name'), max_length=255) uuid = models.CharField(_('uuid'), unique=True, max_length=36) md5sum = models.CharField(_('md5sum'), max_length=32, null=True) filesize = models.PositiveIntegerField(_('Filesize'), null=True) link = models.CharField(_('link'), max_length=1000) meta = JSONField(default=get_empty_dic) create_date = models.DateTimeField(default=timezone.now) conversation = models.ForeignKey('conversation.Conversation', on_delete=models.CASCADE) the architecture of every app are same.means all of app have own signals directory and in signals's directory we have __init__.py and handlers.py files .here is a brief tree of my app with some detail for file's app: apps ├── conversation ├── post └── file ├── admin.py ├── apps.py ├── __init__.py ├── models.py ├── signals │ ├── handlers.py │ └── __init__.py ├── tests.py ├── urls.py └── views.py here is apps/file/signals/handlers.py : from django.db.models.signals import pre_delete from django.dispatch import receiver from apps.file.models import File @receiver(pre_delete, sender=File) def remove_file_from_storage(sender, instance, *args, **kwargs): print('pre_delete signal for File working') # some code is here and app/file/signals/__init__.py file is empty. in this project we are using multiple signals and all of them working fine but i don't know why this signal not working.other signal are from custom and build-in signal both. please notice when i moving def remove_file_from_storage function into … -
when i startapp "article", and python manage.py runserver, and I do not know why "module 'article.admin' has no attribute 'site" this error happen?
I startup an app named "article" but and configure a import like this:from article import * in the setting configure file, then when i run "python manage.py runserver" the error ocuur like this "AttributeError: module 'article.admin' has no attribute 'site', when I comments 'from article import *' with '#', it will work on well, I do not know how "from article import *" raise the problem. when I comments 'from article import *' with '#', it will work on well from article import * atterns = [ path('admin/', admin.site.urls), url(r'^article/',include('article.urls',namespace='article')), ] File "", line 205, in _call_with_frames_removed File "D:\pythonTestfolder\xuegod\blogtest\blogtest\urls.py", line 25, in path('admin/', admin.site.urls), AttributeError: module 'article.admin' has no attribute 'site' -
django 2.1 HTML form submitting to db error
i am trying to post the data from html form to my db, however i get the error that the url does not exist. what am trying to do is later on turn the test form into dynamic add fields using HTML and Jquery rather than using formset for ease UI designing and handle it in dango back end. also note that am assigning the foreign key which is the startup_name by passing it through the url to test view. the code is as following: models.py: class Startup(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) startup_name = models.CharField('Startup Name', max_length = 32, null = False, blank = False) class Team (models.Model): str_team = models.ForeignKey(Startup, on_delete=models.CASCADE) name = models.CharField('Name',max_length = 32, null = False, blank = False) position = models.CharField('Title/Position', max_length = 32, null = False, blank = False) qualification = models.CharField('Degrees/Qualifications', max_length=32,null=False,blank=False) views.py: def create_startupform(request): if request.method == 'POST': form = startupform(request.POST) if form.is_valid(): result = form.save(commit=False) result.author = request.user result.save() return redirect('test', startup_id = result.pk) else: form = startupform() return render(request, 'str_name.html', {'form': form}) def test (request, startup_id): stup = Startup.objects.get(id=startup_id) if request.method == 'POST': na = request.POST.get("name") po = request.POST.get("position") qu = request.POST.get("qualification") ref = Team(name = na, position = po, … -
How to run celery in django tests using PyCharm
I'm trying to test my django application functionalities. Some of my tasks are using celery. How can I run celery in my test environment using PyCharm?